从文件输入中查找java中的最大值 [英] Find max value in java from file input
问题描述
我是Java的新手,我正在尝试编写一个程序,要求用户输入仅包含数字的txt文件的名称,程序将输出数字的总和,平均值,最大值和最小值在文件中。我已经编写了大部分程序,但是我很难找到值的最大值和最小值。您可以提供的任何信息都会有所帮助,如果我不够清楚,我可以尝试详细说明。到目前为止我的代码是:
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
推荐答案
声明两个int变量 - 一个min和一个max。
用Integer.MAX_VALUE初始化min,用Integer.MIN_VALUE初始化最小值。
Declare two int variables - one "min" and one "max". Initialize min with Integer.MAX_VALUE and max with Integer.MIN_VALUE.
然后在你的while循环中检查每个数字对这些变量 - 即。如果number小于min,则将其指定为新的min值。
如果它大于max,则将其指定为新的max值。
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.
这篇关于从文件输入中查找java中的最大值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!