简体   繁体   中英

Find the MIN/MAX/SUM from a Text File

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)

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

}

   

You can simply use IntSummaryStatistics from an 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);
  }
}

Try it online!

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM