在 Java 中使用文本文件查找数字的平均值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33615180/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 21:55:19  来源:igfitidea点击:

Find Average of numbers using a Text File in Java

javafileaveragefilereader

提问by Frazer Pinheiro

package txtfileaverage;

import java.io.*;
import java.util.Scanner;

/**
 *
 * @author Frazer
 */
public class Txtfile {

    public static void main(String args[])  throws IOException
     {
        Scanner file = new Scanner(new File("input.txt")); 

        int numTimes = file.nextInt();
        file.nextLine();

            for(int i = 0; i < numTimes; i++);
            {   
                int sum = 0;
                int count = 0;
              Scanner split = new Scanner(file.nextLine());
              while(split.hasNextInt())
                //for (int a = 0; a < 4 ; a++)
                {
        sum += split.nextInt();
        count++;
                }    
        System.out.println("the average is = " + ((double)sum / count));

            }
                }

}

Text File:

文本文件:

4

100 100 100 100

100 100 50  50

100 90  80  70

60  50  40  30 

the above is the text file i am trying to read from, the output that is displayed is

以上是我试图读取的文本文件,显示的输出是

"the average is 100" but it either only looks at one number or 1 line, any tips on how to get it to read the other lines? i have had a look at some tutorial and after comparing the code i'm struggling to find out why it's only finding the average of 1 number or 1 line rather than the whole row, each with another statement.

“平均值是 100”,但它要么只查看一个数字,要么只查看 1 行,关于如何让它阅读其他行的任何提示?我看过一些教程,在比较了代码之后,我正在努力找出为什么它只找到 1 个数字或 1 行的平均值,而不是整行,每个都有另一个语句。

回答by Arpit Aggarwal

With Java 8 Collectors.averagingInt, it is as simple as:

使用 Java 8 Collectors.averagingInt,它很简单:

 Arrays.stream(Files.lines(Paths.get(ClassLoader.getSystemResource(
                    "input.txt").toURI())).reduce((a, b) -> a + " " + b)
.map(e -> e.split(" ")).get()).filter(e -> e.matches("\d+"))
.map(Integer::new)
.collect(Collectors.averagingInt(Integer::intValue));

Usage:

用法:

import java.io.IOException;
import java.net.URISyntaxException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.stream.Collectors;

public class FindAverage {

    public static void main(String[] args) throws IOException,
            URISyntaxException {

        Double average = Arrays
                .stream(Files
                        .lines(Paths.get(ClassLoader.getSystemResource(
                                "input.txt").toURI()))
                        .reduce((a, b) -> a + " " + b).map(e -> e.split(" "))
                        .get()).filter(e -> e.matches("\d+"))
                .map(Integer::new)
                .collect(Collectors.averagingInt(Integer::intValue));

        System.out.println("Average = " + average);
    }
}

回答by user10780994

Here is a simple way to calculate the average from a text file. Just write an if statement within the while loop.

这是从文本文件计算平均值的简单方法。只需在 while 循环中写一个 if 语句。

See Code Here

在这里查看代码

回答by Meeesh

This code here should work. What I am doing here is going through the file line by line with the while loop. With each line, I am splitting the parts by your specified delimiter, space. Then, I loop through the elements, trim()it which removes excess spaces, grab the integer, and add it to sum. For each of the integers I take, I add to count. At the very end it's the same as yours.

这里的代码应该可以工作。我在这里所做的是使用 while 循环逐行浏览文件。对于每一行,我都按您指定的分隔符空格分割部分。然后,我遍历元素,trim()它删除多余的空格,获取整数,并将其添加到总和。对于我取的每个整数,我添加计数。最后它和你的一样。

import java.io.File;
import java.io.IOException;
import java.util.Scanner;

public class Test {

    public static void main(String args[]) throws IOException {

        Scanner file = new Scanner(new File("input.txt"));

        String line = null;
        int sum = 0;
        int count = 0;
        while ((line = file.nextLine()) != null) {
            String[] vals = line.split(" ");
            for(int i = 0; i < vals.length; i++) {
                sum += Integer.valueOf(vals[i].trim());
                count++;
            }
        }
        System.out.println("the average is = " + ((double) sum / count));

    }

}