从文本文件中查找MINMAXSUM。

问题描述 投票:0回答:1

输入文本文件。

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

最多:1、2、3、5、6人

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

从文本文件的数字列表中获取MINMAX和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)
java arrays max average min
1个回答
1
投票

也许下面是使用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

0
投票

当对文件进行读写时,一定要在处理结束后关闭资源。你可以找到多种方法来做到这一点。请看 https:/docs.oracle.comjavasetutorialessentialexceptionstryResourceClose.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());
    }

0
投票

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

热门问题
推荐问题
最新问题