从CSV文件中读取双倍

时间:2018-06-03 17:45:05

标签: java csv parsing save

我正在尝试编写一个程序来计算赢得彩票的几率/成本。之前的总花费和运行次数分别以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;
}
}

0 个答案:

没有答案