从文本文件中查找最小值/最大值/总和

huangapple go评论73阅读模式
英文:

Find the MIN/MAX/SUM from a Text File

问题

package net.codejava;

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

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 {
        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 {
            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("The min of " + Arrays.toString(minArray) + " is " + Arrays.stream(minArray).min().getAsInt());
        System.out.println("The max of " + Arrays.toString(maxArray) + " is " + Arrays.stream(maxArray).max().getAsInt());
        System.out.println("The avg of " + Arrays.toString(sumArray) + " is " + Arrays.stream(sumArray).average().getAsDouble());
    }
}

Please note that the code itself does not contain any translation of the comments and string literals, as per your request.

英文:

Input Text File:

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

Get the MIN/MAX and SUM from the list of numbers in the text file.

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

Desired Output:

>The min of [1, 2, 3, 5, 6] is 1
>
>The min of [1, 2, 3, 5, 6] is 6
>
>The avg of [1, 2, 3, 5, 6] is 3.4

Current Output:

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)

答案1

得分: 1

以下是翻译好的部分:

也许使用 Arrays.stream 方法解决这个问题的最简单方式如下

文件格式

    最小值1,2,3,5,6
    最大值1,2,7,5,6
    平均值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 {
    //声明变量
            int min ;
            int max ;
            double avg ;
            int sum;
            int count = 0;
            String[] numArray = new String[3];
            int[] maxArray;
            int[] minArray;
            int[] sumArray;
    
    //读取文本文件('input.txt')
    
                String fileName = "input.txt";
                Scanner input = new Scanner(new FileReader(fileName));
    
    //读取数字。获取计数。
            while (input.hasNext()) {
                numArray[count] = input.next();
                count++;
            }
    
    // 将逗号分隔的字符串转换为整数数组,同时从字符串中移除 Min:、Max: 和 Avg: 模式
    
            minArray = toIntArray(numArray[0].replaceAll("Min:",""),",");
            maxArray = toIntArray(numArray[1].replaceAll("Max:",""),",");
            sumArray = toIntArray(numArray[2].replaceAll("Avg:",""),",");
    
    // 使用 arrays.stream 来查找最小值、最大值、总和和平均值。最后一行生成总和和平均值
    
            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);
            System.out.println(" 最大值     " + max);
            System.out.println(" 总和     " + sum);
            System.out.println(" 平均值 " + avg);
    
    
        }
    }

输出如下

     最小值     1
     最大值     7
     总和     17
     平均值 3.4
英文:

Perhaps one of the simplest way of solving this using Arrays.stream method is below,

File Format :

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

Java code :

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

Output is below,

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

答案2

得分: 1

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 / (float) 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);
    }

}
英文:
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(&quot;input.txt&quot;);
File output = new File(&quot;output.txt&quot;);
//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(&quot;min&quot;)) {
getMin(numList, writer);
} else if (line.toLowerCase().startsWith(&quot;max&quot;)) {
getMax(numList, writer);
} else if (line.toLowerCase().startsWith(&quot;avg&quot;)) {
getAverage(numList, writer);
} else if (line.toLowerCase().startsWith(&quot;p&quot;)) {
getPercentile(numList, line, writer);
} else if (line.toLowerCase().startsWith(&quot;sum&quot;)) {
getSum(numList, writer);
}
}
writer.close();
} catch (FileNotFoundException e) {
System.out.println(e + &quot;File not found&quot; );
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(&quot;,&quot;);
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 &lt; numList.length; i++) {
sum = sum + numList[i];
}
float average = sum / numList.length; 
// Write average number to file 
writer.format(&quot;The average of &quot; + Arrays.toString(numList) + &quot; is %.1f\n&quot;, average);
}
//calculate the sum 
public static void getSum(int[] numList, PrintWriter writer) {
// Iterate through the array 
int sum = 0;
for (int i = 0; i &lt; numList.length; i++) {
sum = sum + numList[i];
}
// Write sum to file
writer.println(&quot;The sum of &quot; + Arrays.toString(numList) + &quot; is &quot; + sum);
}
// Get min number
public static void getMin(int[] numList, PrintWriter writer) {
int min = numList[0]; 
for (int i = 1; i &lt; numList.length; i++) {
if (numList[i] &lt; min) {
min = numList[i];
}
}
//Write to file
writer.println(&quot;The min of &quot; + Arrays.toString(numList) + &quot; is &quot; + min);
}
// Get Max number
public static void getMax(int[] numList, PrintWriter writer) {
int max = numList[0];
for (int i = 1; i &lt; numList.length; i++) {
if (numList[i] &gt; max) {
max = numList[i];
}
}
//Write to file
writer.println(&quot;The max of &quot; + Arrays.toString(numList) + &quot; is &quot; + 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(&quot;The %.0f&quot; + &quot;th percentile of &quot; + Arrays.toString(numList)
+ &quot; is &quot; + numList[indexPercentile] + &quot;\n&quot;, percentile * 100);
}
}

答案3

得分: 1

你可以简单地使用 IntSummaryStatistics 来自 IntStream::summaryStatistics

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

在线尝试!

英文:

You can simply use IntSummaryStatistics from an IntStream::summaryStatistics.

<!-- language-all: lang-java -->

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(&quot;min: %d%nmax: %d%nsum: %d%navg: %.2f%n&quot;,
statistics.getMin(),
statistics.getMax(),
statistics.getSum(),
statistics.getAverage()
);
}
private static IntStream intsFromStream(InputStream in) {
Scanner scanner = new Scanner(in);
Spliterator&lt;String&gt; 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!

TIO-kcmirsew: https://tio.run/##dVJrSwJBFP3ur7gEwho2kFEfNANJA8EHuBlBRNx0XMZ2ZpaZu5tS/nabfeUmuV/m7jnnvs7MGhO8WC8/9nshI20I1g5gQrPzTq2KxCTCfzFLhqNMqSh@D8UCFiFaC2MUCr5qAAVqCckdiRZLkI7zfDJCBS@vgCawjUwKMFTkx1Ki2fqp3roUm6fmYReEIvtgtPSztp6/tcQlE6qR5acfs8cVvEYnYwuxjolFrjmtvDMpVBvqy7qSuMkDl50HmAQuYK1VXZ01f6sfhmEBp7FbpHGSxM1p0q15muwl3GDAvXKpbP5daqYRCRIv3Uztynw4tmWoovhAle76C1SKG7DF2QXFP0vUc7rCpigU5AYgbW7zW7oDe8BcWkVhWYXyispNGGkVsHHv@e2pN5oPmtUMNp31B7NBH77/oJPpZDIfjYoZDKfYKMhX8OMofXTFU/MqDZuwwtDyyuVrdR9qy8tJ2u1F@lsRSIwetTPOeUQ8SBUJhjGfrgqTd/v9JbTgCq7h5gc "Java (JDK) – Try It Online"

答案4

得分: 0

当阅读和写入文件时,请务必在处理完成后始终关闭资源。您可以找到多种方法来做到这一点。有关处理资源的信息,请参阅 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) {
        //做一些操作... 文本文件将是字符串类型。
        input = bufferedReader.readLine();
    }

} catch (FileNotFoundException e) {
    System.out.println("文件未找到 " + fileName.getName());
} catch (IOException e) {
    System.out.println("处理文件时出错 " + fileName.getName());
}
英文:

When reading and writing too and from files be sure to always close the resource when processing has finished. You can find multiple ways to do this. See https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html for information on handling resources.

    File fileName = new File(&quot;input.txt&quot;);
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(&quot;File not found &quot; + fileName.getName());
} catch (IOException e) {
System.out.println(&quot;Error processing file  &quot; + fileName.getName());
}

答案5

得分: 0

你可以将 while 循环中的条件替换为:while (input.hasNext()) {,然后在之后检查输入是否为整数。

英文:

You could replace the condition in the while loop with: while(input.hasNext()) { and check after if the input is an int

huangapple
  • 本文由 发表于 2020年5月5日 00:28:46
  • 转载请务必保留本文链接:https://go.coder-hub.com/61597013.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定