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

问题描述 投票:-2回答:1

我的任务是使用扫描仪导入读取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

如您所见,我没有走得很远,我无法弄清楚。谢谢您的帮助。

java file java.util.scanner average throws
1个回答
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;
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.