在文本文件中添加双打的代码? Java

Code for adding doubles within a text file? Java

我想知道下面的代码 returns 是否是文本文件中所有双打的总和。当我测试运行它时,它似乎总是显示为 0.0。可能是什么问题呢?我

public double honorsCalculation() throws IOException {
    Scanner test = new Scanner(new File("Calculus - Test.txt"));
    while (test.hasNext()) {
        ArrayList <Double> assignments = new ArrayList <Double> ();
        double num = test.nextDouble();
        assignments.add(num);
        for (int i = 1; i < assignments.size() - 1; i++) {
            sum = sum + assignments.get(i);
            percentage = sum;
        }
    }
    return percentage;
}

您在阅读所有数据之前正在处理信息。

public double honorsCalculation() throws IOException {
    Scanner test = new Scanner(new File("Calculus - Test.txt"));
    ArrayList <Double> assignments = new ArrayList <Double> ();
    while (test.hasNext()) {
        double num = test.nextDouble();
        assignments.add(num);
    }
    for (int i = 1; i < assignments.size() - 1; i++) {
        sum = sum + assignments.get(i);
        percentage = sum;
    }
    return percentage;
}

这应该是正确的做法。

您根本不需要 ArrayList,并且很难看出百分比如何等于总和,或者您的变量在哪里被初始化:

public double honorsCalculation() throws IOException {
    double sum = 0;
    Scanner test = new Scanner(new File("Calculus - Test.txt"));
    while (test.hasNext()) {
        sum += test.nextDouble();
    }
    return sum;
}