从文件输入中查找java中的最大值

我是Java的新手,我正在尝试编写一个程序,要求用户输入仅包含数字的txt文件的名称,程序将输出文件中数字的总和,平均值,最大值和最小值。 我已经编写了大部分程序,但是我很难找到值的最大值和最小值。 您可以提供的任何信息都会有所帮助,如果我不够清楚,我可以尝试详细说明。 到目前为止我的代码是:

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 

有两个变量min和max(当然min和max最初应该是int.max)提示:

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

以上内容将在您的文件读取循环中。

声明两个int变量 – 一个“min”和一个“max”。 使用Integer.MAX_VALUE初始化min,使用Integer.MIN_VALUE初始化max。

然后在你的while循环中检查每个数字对那些变量 – 即。 如果number小于“min”,则将其指定为新的“min”值。 如果它大于“max”,则将其指定为新的“max”值。

希望这澄清,它非常简单,所以我没有放任何代码,所以你可以自己实现它。

 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 

将最小值声明为最大int值,并在每次读取小于当前最小值的新值时重新指定最小值。 同样的事情是最大的价值。

我有一个实例,我需要从包含大量插入语句的.sql文件中找到最大的Id。 这些语句还插入了Id以及所有其他字段。 我认为这将是一个很好的例子,因为该文件不仅有整数而且有大量的混合数据类型。 以下是我的节目,

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