【问题标题】:How do I read content from a .txt file and then find the average of said content in Java?如何从 .t​​xt 文件中读取内容,然后在 Java 中找到所述内容的平均值?
【发布时间】:2019-11-20 00:38:45
【问题描述】:

我的任务是使用扫描仪导入读取 data.txt 文件。 data.txt 文件如下所示:

1 2 3 4 5 6 7 8 9 问

我需要阅读并找到这些数字的平均值,但是当我得到一个不是整数的东西时就停下来。

这是我目前的代码。

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

如您所见,我没有走多远,我无法弄清楚这一点。感谢您的帮助。

【问题讨论】:

    标签: java file java.util.scanner average throws


    【解决方案1】:

    首先,您的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;
        }
    }
    

    【讨论】:

    • 那我该如何调用这个方法呢?我无法调用 fileAverage(filename);之后的任何地方,因为它说代码无法访问或说返回类型丢失?
    • fileAverage(filename); - 在这里工作正常。你怎么称呼它?是哪个错误?您的目标是什么版本的 Java?
    • 我正在使用 javaSE-12 并在定义方法后放置它。我收到错误提示无法访问代码、方法缺少返回类型以及语法错误插入变量声明器ID。
    • 因为你不能调用一个方法而不是在一个块中(通常在main)。
    • 对。好的,我发现了我的问题并让一切正常工作。非常感谢您的帮助!
    猜你喜欢
    • 2014-03-17
    • 1970-01-01
    • 1970-01-01
    • 2011-05-03
    • 2013-02-14
    • 1970-01-01
    • 1970-01-01
    • 2012-01-29
    • 1970-01-01
    相关资源
    最近更新 更多