[英]How do I read content from a .txt file and then find the average of said content in Java?
我的任务是使用扫描仪导入读取 data.txt 文件。 data.txt 文件如下所示:
1 2 3 4 5 6 7 8 9 问
我需要阅读并找到这些数字的平均值,但是当我遇到不是 integer 的东西时停止。
这是我到目前为止的代码。
public static double fileAverage(String filename) throws FileNotFoundException {
Scanner input = new Scanner(System.in);
String i = input.nextLine();
while (i.hasNext);
return fileAverage(i); // dummy return value. You must return the average here.
} // end of method fileAverage
如您所见,我并没有走得太远,我无法弄清楚。 谢谢您的帮助。
首先,您的Scanner
应该在文件filename
上(而不是System.in
)。 其次,您应该使用Scanner.hasNextInt()
和Scanner.nextInt()
(不是Scanner.hasNext()
和Scanner.nextLine()
)。 最后,您应该将读取的每个int
添加到运行total
中,并跟踪读取的数字count
。 而且,我会使用try-with-resources
语句来确保Scanner
已关闭。 就像是,
public static double fileAverage(String filename) throws FileNotFoundException {
try (Scanner input = new Scanner(new File(filename))) {
int total = 0, count = 0;
while (input.hasNextInt()) {
total += input.nextInt();
count++;
}
if (count < 1) {
return 0;
}
return total / (double) count;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.