问题从文本文件中读取

时间:2018-06-03 03:04:50

标签: java save text-files average

我正在尝试用Java创建一个程序来计算赢得彩票的平均成本,并在再次运行时保存该平均值以供参考(我的目标是每次运行时都能创建更准确的结果) 。平均成功保存到我的txt文件,但是当我运行程序时,它每次都使用0作为之前的平均值。任何帮助是极大的赞赏!谢谢! (运行次数可以通过更改'运行变量)来改变

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;
}
}

2 个答案:

答案 0 :(得分:0)

在读取之前的值之前,请尝试不构造PrintWriter。如Javadoc中所述,文件将通过创建PrintWriter而被截断。

答案 1 :(得分:0)

您的代码在覆盖模式下打开文件,默认情况下是许多编程语言,然后扫描程序才能读取内容,从而在fileScanner.hasNextDouble()读取之前删除内容。在扫描仪读取后移动您的PrintWriter实例,它将起作用。

注意:要以附加模式打开文件,我认为你不需要这里。但是在Java中你使用新的FileWriter(&#34; average.txt&#34;,true)然后在它周围包装一个PrintWriter。