简体   繁体   English

从文本文件读取问题

[英]Issue Reading from text file

I am trying to create a program in Java that calculates the average cost of winning the lottery and saves that average to reference when it runs again (my goal is to be able to create a more accurate outcome every time i run it). 我正在尝试用Java创建一个程序,该程序计算中奖的平均成本,并在再次运行该平均数时保存该平均数以供参考(我的目标是每次运行它都能够创建更准确的结果)。 The average successfully saves to my txt file, but when I run the program it uses 0 as the previous average every time. 该平均值成功保存到我的txt文件中,但是当我运行该程序时,每次都使用0作为以前的平均值。 Any help is greatly appreciated! 任何帮助是极大的赞赏! Thanks! 谢谢! (Number of times it runs can be changed by changing the 'runs' variable) (它的运行次数可以通过更改“运行”变量来更改)

public class WinningTheLottery
{
public static final int SIZE = 5;

public static void main(String[] args)
{
    int[] winningNums = new int[SIZE];
    int[] guessNums = new int[SIZE];
    int spent, runs = 1;
    double oldAvg = 0;
    double newAvg;
    int totalSpent = 0;
    NumberFormat currency = NumberFormat.getCurrencyInstance();
    try
    {
        Scanner fileScanner = new Scanner(new File("average.txt"));
        PrintWriter fileWriter = new PrintWriter(new File("average.txt"));
        while (fileScanner.hasNextDouble())
        {
            oldAvg = fileScanner.nextDouble();
        }
        for (int i = 0; i < runs; i++)
        {
            spent = 0;
            randomlyAssignedNumbers(winningNums);
            // Arrays.toString(nameOfArray) => built in method to print an array
            System.out.println("\n[" + (i+1) + "] Todays winning numbers:\n" + Arrays.toString(winningNums).replace("[", "").replace("]", ""));
            do
            {
                randomlyAssignedNumbers(guessNums);
                spent++;
            } while (howManyCorrect(winningNums, guessNums) < 5);
            System.out.println("After spending " + currency.format(spent) + ", you won the Fantasy 5 lottery $75,000 prize!");
            totalSpent += spent;
        }
        newAvg = ((totalSpent/runs) +oldAvg)/2;
        fileWriter.println(newAvg);
        System.out.println("\nAverage Cost to win the Lottery: " + currency.format(newAvg)
                        + "\n(Previous Average: " + currency.format(oldAvg) + ")");
        fileScanner.close();
        fileWriter.close();
    }
    catch(IOException e)
    {
        System.out.println(e.getMessage());
    }

}

public static void randomlyAssignedNumbers(int[] anyArray)
{
    Random rng = new Random();
    for (int i = 0; i < anyArray.length; i++)
    {
        anyArray[i] = rng.nextInt(36) + 1;
    }
}

public static int howManyCorrect(int[] a1, int[] a2)
{
    if (a1.length != a2.length)
        return -1;
    int count = 0;
    for (int i = 0; i < a1.length; i++)
    {
        if (a1[i] == a2[i])
            count++;
    }
    return count;
}
}

Try not constructing the PrintWriter until after you read the previous value. 在读取之前的值之前,请尝试不要构造PrintWriter。 As noted in the Javadoc the file will be truncated by creating the PrintWriter. Javadoc中所述,将通过创建PrintWriter将文件截断。

Your code is opening the file in overwrite mode, default of many programming languages, before scanner can read the content, thus deleting the content before fileScanner.hasNextDouble() read. 在扫描程序可以读取内容之前,您的代码将以覆盖模式(许多编程语言的默认设置)打开文件,从而在fileScanner.hasNextDouble()读取之前删除内容。 Move your PrintWriter instantiation after Scanner read, and it will work. 扫描程序读取后,移动您的PrintWriter实例,它将起作用。

Note: To open the file in append mode, which I don't think you need here. 注意:要以追加模式打开文件,我认为您不需要在这里。 But in Java you use new FileWriter("average.txt", true) and then wrap a PrintWriter around it. 但是在Java中,您使用新的FileWriter(“ average.txt”,true),然后在其周围包装一个PrintWriter。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM