Find max value in java from file input

2020-05-04 05:49发布

I'm new to Java and I am trying to write a program that asks the user to input the name of a txt file containing only numbers, and the program will output the sum, average, max, and min of the numbers in the file. I have written most of the program, however I am stuck trying to find the max and min of the values. Any information you can give would be helpful, and if I was not clear enough I can try to elaborate. My code so far is:

public class NumberFile{
    public static void main(String[] args){

      boolean goodName = false;
      int currentNumber, sum = 0, numberCount=0;
      Scanner numberFile = null;
      FileReader infile; 

      Scanner input = new Scanner(System.in);
      System.out.println("Please enter the name of the file you wish to import: ");
      String fileName = input.nextLine();



      while (!goodName){
        try{
          infile = new FileReader(fileName);
          numberFile = new Scanner(infile);
          goodName = true;
        }
        catch (IOException e){
          System.out.println("invalid file name, please enter another name");
          fileName = input.nextLine();
        }
      }
      while (numberFile.hasNextInt()){
        currentNumber = numberFile.nextInt();
        sum+=currentNumber;
        numberCount++;
      }
      System.out.println("The sum of the numbers is " +sum);

      System.out.println("The average of the numbers is " + ((double) sum)/numberCount);



    } // end main
} // end class

标签: java max min
4条回答
再贱就再见
2楼-- · 2020-05-04 06:08

I had an instance where I needed to find the largest Id from an .sql file containing large set of insert statements. These statements also inserted the Id along with all other fields. I thought this will make a good example as the file not only has integers but large chunk of mixed data types. Below is my program,

import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Scanner;

/**
 * @author Hamzeen. H.
 * @date 15/10/2015
 */
public class Driver {

    public Driver() {
    }

    private void readData() {
        try {
            Scanner inputFile = new Scanner(new DataInputStream(
                    new FileInputStream("all_inserts.sql")));
            long highest = 0L;

            while (inputFile.hasNext()) {
                String strNum = buildNumber(inputFile.next());

                if (!strNum.equals("")) {
                    Long temp = Long.parseLong(strNum);
                    if (temp > highest) {
                        highest = temp;
                    }
                }
            }
            System.out.println("Highest:: " + highest);
            inputFile.close();
        } catch (IOException e) {
            System.out.println("Problem finding file");
        }
    }

    private String buildNumber(String str) {
        StringBuilder strBuilder = new StringBuilder();

        for (int i = 0; i < str.length(); i++) {
            char ch = str.charAt(i);
            if (Character.isDigit(ch)) {
                strBuilder.append(ch);
            } else if ('.' == ch || !Character.isDigit(ch) || ',' == ch) {
                return strBuilder.toString().trim();
            }
        }
        return strBuilder.toString().trim();
    }

    public static void main(String args[]) {
        new Driver().readData();
    }
}
查看更多
不美不萌又怎样
3楼-- · 2020-05-04 06:13

Declare two int variables - one "min" and one "max". Initialize min with Integer.MAX_VALUE and max with Integer.MIN_VALUE.

Then within your while loop check every number against those variables - ie. if number is smaller than "min" then assign it as a new "min" value. If its larger than "max" then assign it as new "max" value.

Hope this clarifies, its very simple so I didnt put any code so you can implement it yourself.

查看更多
在下西门庆
4楼-- · 2020-05-04 06:14
int min=Integer.MAX_VALUE;
int max=Integer.MIN_VALUE;
while (numberFile.hasNextInt()){
   currentNumber = numberFile.nextInt();
   sum+=currentNumber;
   numberCount++;

   if(min>currentNumber){
      min=currentNumber;
    }
   if(max<currentNumber){
      max=currentNumber;
    }
}

Declare the minimum value to the maximum int value and reassign the minimum value every time you read new value that is smaller than current minimum value. Same thing goes for maximum value.

查看更多
ゆ 、 Hurt°
5楼-- · 2020-05-04 06:19

Have two variables min and max (of course min and max should initially be int.max) Hint:

if(currentNumber < min)
{
  min= currentNumber;
}

if(currentNumber > max)
{
 max = currentNumber 
}

The above would be in your file read loop.

查看更多
登录 后发表回答