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

时间:2015-01-08 05:32:33

标签: java file text

我想知道以下代码是否返回文本文件中所有双精度的总和。当我测试它时,它似乎总是显示为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;
}

2 个答案:

答案 0 :(得分:1)

根本不需要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;
}

答案 1 :(得分:0)

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

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

这应该是正确的方法。