作者:jx轩宝妈咪 | 来源:互联网 | 2023-10-11 16:30
我的任务是使用扫描仪导入功能读取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;
}
}