Java IO "NaN"问题

标签 java eclipse

我有一个名为 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

最佳答案

你需要做

double average = total/count;

之后您将获得totalcount的值

但是还要注意

while (scan.hasNext()) 流耗尽时,while (scan.hasNextDouble()) 也将耗尽

这个问题可以克服,但只需循环一次

关于Java IO "NaN"问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58967310/

相关文章:

java - 注释方法 arg @Nonnull 时 JUnit 测试失败

Java随机类输出1或0

Java hibernate/C3P0 错误 : "Could not obtain connection metadata. An attempt by a client to checkout a Connection has timed out."

eclipse - 如何更改 Eclipse 的编辑器以在多列中显示或编辑代码?

java - Eclipse - 启动时发生错误/查看日志文件

java - servlet java.lang.NoClassDefFoundError : org/apache/commons/lang/Validate 中未捕获的异常

java - Android Studio : W/OpenGLRenderer: Failed to choose config with EGL_SWAP_BEHAVIOR_PRESERVED

c++ - 我无法将字符与输入进行比较。具体到 "\"的字符串中的一个字符

java - 在没有反应堆的情况下按顺序清理/安装多个maven项目

java - 在 Eclipse 中发布应用程序时替换属性文件的内容