我觉得我犯了一个非常简单的错误,但我不知道它是什么。我知道程序正在读取正确的文件,但每次运行该程序时,它只是返回 0.0000 作为总和。我做错了什么?
最佳答案
您使用了错误的Scanner构造函数,即您正在从字符串 filename
中读取的构造函数。我测试过这个,
// Why void? Just return the sum
public double readFile(String filename) {
Scanner input = null;
double sum = 0;
try {
input = new Scanner(new File(filename));
while (input.hasNextDouble()) {
sum += input.nextDouble();
}
// output results
System.out.printf("The total sum of the "
+ "doubles in the input file is %f\n", sum);
} catch (FileNotFoundException e) {
e.printStackTrace();
} finally {
input.close();
}
我得到了输出
The total sum of the doubles in the input file is -3.651000
关于java - 使用 Java 从文本文件中读取/求和数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21128069/