【问题标题】:Find Average of numbers using a Text File in Java使用 Java 中的文本文件查找数字的平均值
【发布时间】:2015-11-09 17:55:16
【问题描述】:
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));

            }
                }

}

文本文件:

4

100 100 100 100

100 100 50  50

100 90  80  70

60  50  40  30 

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

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

【问题讨论】:

    标签: java file average filereader


    【解决方案1】:

    使用 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));
    

    用法:

    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);
        }
    }
    

    【讨论】:

      【解决方案2】:

      这里的代码应该可以工作。我在这里所做的是使用 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));
      
          }
      
      }
      

      【讨论】:

        【解决方案3】:

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

        See Code Here

        【讨论】:

        • 请在此处添加代码,请勿提供代码截图链接。
        猜你喜欢
        • 1970-01-01
        • 2017-06-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-02-18
        • 1970-01-01
        相关资源
        最近更新 更多