【问题标题】:Find the MIN/MAX/SUM from a Text File从文本文件中查找 MIN/MAX/SUM
【发布时间】:2020-08-19 03:52:54
【问题描述】:

输入文本文件:

最小值:1,2,3,5,6

最大:1,2,3,5,6

平均:1,2,3,5,6

从文本文件中的数字列表中获取 MIN/MAX 和 SUM。

package net.codejava;

import java.io.FileReader;
import java.util.Scanner;
import java.io.FileNotFoundException;
import java.util.Arrays;
import java.util.Formatter;

public class MyFile {
       public static int[] toIntArray(String input, String delimiter) {

            return  Arrays.stream(input.split(delimiter)).mapToInt(Integer::parseInt).toArray();
    }
    public static void main(String[] args) throws FileNotFoundException {
        //Declare Variables
        int min = Integer.MAX_VALUE;
        int max = Integer.MIN_VALUE;
        double avg = 0.0;
        int sum = 0;
        int count = 0;
        String[] numArray = new String[30];
        int[] maxArray;
        int[] minArray;
        int[] sumArray;

        try {
            //Read the text file ('input.txt')
            String myFile = "input.txt";
            Scanner input = new Scanner(new FileReader(myFile));    
            while(input.hasNext()) {
                input.next();
                numArray[count] = input.next();
                count++;
                }
        } catch(FileNotFoundException e) {
            System.out.println("File not found!");  
        }

        minArray = toIntArray(numArray[0],",");
        maxArray = toIntArray(numArray[1],",");
        sumArray = toIntArray(numArray[2],",");
        
        System.out.println(" Min Value " + Arrays.stream(minArray).min().getAsInt());
        System.out.println(" Max Value " + Arrays.stream(maxArray).max().getAsInt());
        System.out.println(" Sum Value " + Arrays.stream(sumArray).sum());
    }
}

期望的输出:

[1, 2, 3, 5, 6] 的最小值为 1

[1, 2, 3, 5, 6] 的最小值是 6

[1, 2, 3, 5, 6] 的平均值是 3.4

电流输出:

Exception in thread "main" java.util.NoSuchElementException

    at java.base/java.util.Scanner.throwFor(Scanner.java:937)

    at java.base/java.util.Scanner.next(Scanner.java:1478)

    at net.codejava.MyFile.main(MyFile.java:32)

【问题讨论】:

  • 如果文件有非int值,input.hasNextInt()返回false,此时while循环结束
  • @b1ack_char1ie - 请检查最新的解决方案并发表评论。

标签: java arrays sum max min


【解决方案1】:

在读取和写入文件时,请务必在处理完成后始终关闭资源。您可以找到多种方法来做到这一点。有关处理资源的信息,请参阅https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html

    File fileName = new File("input.txt");

    try(FileReader fileReader = new FileReader(fileName);
        BufferedReader bufferedReader = new BufferedReader(fileReader);){

        String input = bufferedReader.readLine();

        while(input != null) {
            //Do something... text file will be of type String.
            input = bufferedReader.readLine();
        }

    } catch (FileNotFoundException e){
        System.out.println("File not found " + fileName.getName());
    } catch (IOException e) {
        System.out.println("Error processing file  " + fileName.getName());
    }

【讨论】:

    【解决方案2】:

    您可以将 while 循环中的条件替换为:while(input.hasNext()) { 并检查输入是否为 int

    【讨论】:

      【解决方案3】:

      也许使用 Arrays.stream 方法解决此问题的最简单方法之一如下,

      文件格式:

      Min:1,2,3,5,6
      Max:1,2,7,5,6
      Avg:1,2,3,5,6
      

      Java 代码:

      package org.personal.TestProject;
      
      
      import java.io.FileNotFoundException;
      import java.util.Arrays;
      import java.util.Scanner;
      import java.io.FileReader;
      
      
      public final class MinMaxAvg {
      
      
          public static int[] toIntArray(String input, String delimiter) {
      
              return  Arrays.stream(input.split(delimiter))
                      .mapToInt(Integer::parseInt)
                      .toArray();
          }
      
          public static void main(String[] args) throws FileNotFoundException {
      //Declare Variables
              int min ;
              int max ;
              double avg ;
              int sum;
              int count = 0;
              String[] numArray = new String[3];
              int[] maxArray;
              int[] minArray;
              int[] sumArray;
      
      //Read the text file ('input.txt')
      
                  String fileName = "input.txt";
                  Scanner input = new Scanner(new FileReader(fileName));
      
      //Read the numbers. Get count.
              while (input.hasNext()) {
                  numArray[count] = input.next();
                  count++;
              }
      
      // Convert the comma seperated string to Int array after removing Min:, Max: and Avg: pattern from the string
      
              minArray = toIntArray(numArray[0].replaceAll("Min:",""),",");
              maxArray = toIntArray(numArray[1].replaceAll("Max:",""),",");
              sumArray = toIntArray(numArray[2].replaceAll("Avg:",""),",");
      
      // Use arrays.stream to find min,max,sum and average. Sum and average is generated for last line
      
              min = Arrays.stream(minArray).min().getAsInt();
              max = Arrays.stream(maxArray).max().getAsInt();
              sum = Arrays.stream(sumArray).sum();
              avg = Arrays.stream(sumArray).average().getAsDouble();
      
              System.out.println(" Min Value     " + min);
              System.out.println(" Max Value     " + max);
              System.out.println(" Sum Value     " + sum);
              System.out.println(" Average Value " + avg);
      
      
          }
      }
      

      输出如下,

       Min Value     1
       Max Value     7
       Sum Value     17
       Average Value 3.4
      

      【讨论】:

      • 您好,感谢您的回复。是的,这对你来说可能很简单,但现在对我来说并不简单。我正在以初学者级别的方法进行此操作。读取文本文件,获取计数,获取最小值,获取最大值,获取平均值。
      • 如果可行,请标记/投票,否则请根据您面临的实际问题更新问题。
      • 我实现了您的代码,但遇到了一些输出错误。我已经更新了我的帖子。
      • 您似乎在文件的行首有空格,删除空格并再次运行代码。即在“Min:”之前有一个空格。
      • 我看了看,可以确认在 min 之前没有空格。
      【解决方案4】:
      package MyFile;
      import java.io.File;
      import java.io.FileNotFoundException;
      import java.util.Scanner;
      import java.util.Arrays;
      import java.io.PrintWriter;
      
      public class MinMaxAvg {
          public static void main(String[] args) {
      
              // Create File object
              try {
                  File fileName = new File("input.txt");
                  File output = new File("output.txt");
                  
                  //Create Scanner to read file
                  Scanner scnr = new Scanner(fileName);
                  
                  //Output the file line by line
                  PrintWriter writer = new PrintWriter(output);
                  
                  //Read each line of file using Scanner class
                  while (scnr.hasNextLine()) {
                      String line = scnr.nextLine();
      
                      // split the line and place them in an array.
                      int[] numList = splitString(line);
                                      
                      if (line.toLowerCase().startsWith("min")) {
                          getMin(numList, writer);
                          } else if (line.toLowerCase().startsWith("max")) {
                              getMax(numList, writer);
                          } else if (line.toLowerCase().startsWith("avg")) {
                              getAverage(numList, writer);
                          } else if (line.toLowerCase().startsWith("p")) {
                              getPercentile(numList, line, writer);
                          } else if (line.toLowerCase().startsWith("sum")) {
                              getSum(numList, writer);
                          }
                  }
                  writer.close();
      
      
              } catch (FileNotFoundException e) {
                  System.out.println(e + "File not found" );
                  return; 
              }
      
          }
          //End main class
          
          // Class to split 
          public static int[] splitString(String line) {
              // trim the blank spaces on the line
              String shorterLine = line.substring(4).trim();
              
              //split the string 
              String[] list = shorterLine.split(",");
              int listLen = list.length;
              
              // Create an array and iterate through the numbers list
              int[] numList = new int[listLen];
              for (int i = 0; i != listLen; i++) {
                  numList[i] = Integer.parseInt(list[i]);
              }
              return numList;
          }
          
          //Calculate the average number
          public static void getAverage(int[] numList, PrintWriter writer) {
              
              //calculate the sum of the array numbers
              int sum = 0;
              for (int i = 0; i < numList.length; i++) {
                  sum = sum + numList[i];
              }
      
              float average = sum / numList.length; 
      
              // Write average number to file 
              writer.format("The average of " + Arrays.toString(numList) + " is %.1f\n", average);
      
          }
          
          //calculate the sum 
          public static void getSum(int[] numList, PrintWriter writer) {
              // Iterate through the array 
              int sum = 0;
              for (int i = 0; i < numList.length; i++) {
                  sum = sum + numList[i];
              }
      
              // Write sum to file
              writer.println("The sum of " + Arrays.toString(numList) + " is " + sum);
          }
          
          // Get min number
          public static void getMin(int[] numList, PrintWriter writer) {
              int min = numList[0]; 
              for (int i = 1; i < numList.length; i++) {
                  if (numList[i] < min) {
                      min = numList[i];
                  }
              }
              
              //Write to file
              writer.println("The min of " + Arrays.toString(numList) + " is " + min);
      
          }
          
          // Get Max number
          public static void getMax(int[] numList, PrintWriter writer) {
             
              int max = numList[0];
              for (int i = 1; i < numList.length; i++) {
                  if (numList[i] > max) {
                      max = numList[i];
                  }
              }
              
            //Write to file
              writer.println("The max of " + Arrays.toString(numList) + " is " + max);
          }
          
          
          // Get percentile
          public static void getPercentile(int[] numList, String line, PrintWriter writer) {
              // sort the array
              Arrays.sort(numList); 
           
              int parsedInteger = Integer.parseInt(line.substring(1, 3));
              
              // cast to float and divide by 100 to get the percentile
              float percentile = (float) parsedInteger / 100;
              
              // Calculate the index position for percentile
              // minus 1 to accommodate the fact that indexing is from 0
              int indexPercentile = (int) (numList.length * percentile) - 1; 
      
              //Write to file
              writer.format("The %.0f" + "th percentile of " + Arrays.toString(numList)
                      + " is " + numList[indexPercentile] + "\n", percentile * 100);
          }
          
          
      
      }
      
         
      

      【讨论】:

      • 所有format methods 的想法是拥有one 格式字符串和可变的arity 参数,例如避免字符串连接:writer.format("The average of %s is %.1f%n", Arrays.toString(numList), average);。将println() 替换为printf() 也是如此:writer.printf("The sum of %s is %d%n", Arrays.toString(numList), sum);
      【解决方案5】:

      您可以简单地从IntStream::summaryStatistics 中使用IntSummaryStatistics

      import java.io.*;
      import java.util.*;
      import java.util.stream.*;
      public class Main {
        public static void main(String[] args) {
          IntSummaryStatistics statistics = intsFromStream(System.in)
              .summaryStatistics();
          System.out.printf("min: %d%nmax: %d%nsum: %d%navg: %.2f%n",
              statistics.getMin(),
              statistics.getMax(),
              statistics.getSum(),
              statistics.getAverage()
            );
        }
        private static IntStream intsFromStream(InputStream in) {
          Scanner scanner = new Scanner(in);
          Spliterator<String> spliterator = Spliterators.spliterator(scanner, Long.MAX_VALUE, Spliterator.ORDERED | Spliterator.NONNULL);
          return StreamSupport.stream(spliterator, false)
              .onClose(scanner::close)
              .mapToInt(Integer::valueOf);
        }
      }
      

      Try it online!

      【讨论】:

        猜你喜欢
        • 2023-03-13
        • 2017-06-30
        • 1970-01-01
        • 2021-05-04
        • 2018-05-07
        • 2019-07-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多