我有一个名为 Numbers.txt 的文件,其内容如下:
8.5
83.45, 90.2
120.00, 11.05
190.00
我编写的代码使用文件的内容来计算文件中数字的总和和平均值,但是当我运行代码时,对于平均值,结果为“ NaN”
代码:
package lab13;
import java.util.Scanner;
import java.io.*;
public class problem1 {
public static void main(String[] args) throws IOException
{
double sum = 0;
int count = 0;
double num,total = 0;
double average = total/count;
File file = new File("Numbers.txt");
Scanner scan = new Scanner(file);
while (scan.hasNext())
{
double number = scan.nextDouble();
sum = sum + number;
}
while (scan.hasNextDouble())
{
num = scan.nextDouble();
System.out.println(num);
count++;
total += num;
}
scan.close();
System.out.println("The sum of the numbers in " +
"Numbers.txt is " + sum );
System.out.println("The average of the numbers in " +
"Numbers.txt is " + average );
}
}
输出:
Numbers.txt中的数字总和为503.2
Numbers.txt中数字的平均值为NaN
答案 0 :(得分:2)
您需要做
double average = total/count;
之后,您拥有total
和count
但是也请注意
当while (scan.hasNext())
流耗尽时,while (scan.hasNextDouble())
也将耗尽
可以克服,但只需循环一次