我的getMinValue()
方法出现逻辑错误。 getMaxValue()
方法有效,所以我不明白为什么最小方法不起作用。
import java.io.*;
import java.lang.*;
import java.util.*;
public class FILE {
public static void main(String[] main) throws IOException {
int sum = 0;
int counter = 0;
int i = 0;
int[] quizArray = new int[20];
double average = 0.0;
FileReader myReader = new FileReader(
"C:\\Users\\Mike\\Desktop\\QuizScores.txt");
BufferedReader intHunter = new BufferedReader(myReader);
// check through the first line
String line = intHunter.readLine();
// If more line go ahead!
while (line != null) {
// System.out.println("Inside while loop1");
StringTokenizer myTokenizer = new StringTokenizer(line, " ");
while (myTokenizer.hasMoreTokens()) {
// System.out.println("Inside while loop2");
String text = myTokenizer.nextToken();
try {
quizArray[i] = Integer.parseInt(text);
// print valid number
System.out.println(quizArray[i]);
// min & max
sum += quizArray[i];
i++;
counter++;
// System.out.println(quizArray[i]);
} catch (NumberFormatException nfe) {
continue;
}
// extract integers from a text file, then do the calculation.
}
average = (double) sum / counter;
line = intHunter.readLine();
}
intHunter.close();
System.out.println("The new file is: " + counter + " integers as:"
+ " sum = " + sum + " average " + average + "\n"
+ " The max value is " + getMaxValue(quizArray) + "\n"
+ " The min is " + getMinValue(quizArray));
}
// getting the maximum value
public static int getMaxValue(int[] array) {
int maxValue = array[0];
for (int i = 1; i < array.length; i++) {
if (array[i] > maxValue) {
maxValue = array[i];
}
}
return maxValue;
}
// getting the miniumum value
public static int getMinValue(int[] array) {
int minValue = array[0];
for (int i = 1; i < array.length; i++) {
if (array[i] < minValue) {
minValue = array[i];
}
}
return minValue;
}
}
答案 0 :(得分:0)
您正在创建20的数组,因此,如果您指定的值小于20,则将其设置为0.
像: 如果你提供数组
5
6
3
2
1
所以数组的15个元素中的其余部分为0,这就是为什么它给你答案0但是在最大数字中0为min是因此它运行良好。对于您的程序使用动态数组