首页 > 解决方案 > 从 CSV 文件中读取双精度

问题描述

我正在尝试编写一个程序来计算赢得彩票的几率/成本。之前的总花费和运行次数分别作为 double 和 int 保存到 csv 文件中。当我手动将一个数字写入文件中以获取总花费(不含小数点)时,它运行良好,但一旦保存数字,我就无法再次运行它。我相信与用于较大数字的格式和/或使用 parseInt 相关的问题,但我不确定。任何帮助是极大的赞赏。谢谢!

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, oldRuns = 0, totalSpent = 0, bothRuns = 0;
    double oldTotal = 0.0, newAvg, bothTotal = 0.0;
    String line;
    String[] parts;
    NumberFormat currency = NumberFormat.getCurrencyInstance();
    try
    {
        Scanner fileScanner = new Scanner(new File("average.csv"));
        while (fileScanner.hasNextLine())
        {
            line = fileScanner.nextLine();
            parts = line.split(",");
            oldTotal = Integer.parseInt(parts[0]);
            oldRuns = Integer.parseInt(parts[1]);

        }

        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;
        }
        bothTotal = totalSpent + oldTotal;
        bothRuns = runs + oldRuns;
        newAvg = (bothTotal/bothRuns);
        PrintWriter fileWriter = new PrintWriter(new File("average.csv"));
        fileWriter.println(bothTotal + "," + bothRuns);
        System.out.println("\nAverage Cost to win the Lottery: " + currency.format(newAvg));
        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;
}
}

标签: javacsvparsingsave

解决方案


推荐阅读