我的任务是使用扫描仪导入读取data.txt文件。 data.txt文件如下所示:
1 2 3 4 5 6 7 8 9 Q
我需要阅读并找到这些数字的平均值,但是当我得到的不是整数时就停下来。
这是我到目前为止的代码。
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;
}
}