繁体   English   中英

如何从 a.txt 文件中读取内容,然后在 Java 中找到所述内容的平均值?

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM