正如标题所述,我试图找到最大值和最小值、偶数和奇数的数量以及所有输入数字的平均值。
问题。当我运行我的代码时,我的奇数和偶数计数器似乎读取它们的相反值,奇数会读取偶数输入,偶数会读取奇数输入。至于我的平均值,我不知道它有什么问题,我只知道它只会找到适当分数的平均值。
另外,当我输入退出时,我得到了我最大的数字 214XXXXXXXX
我的输出示例将粘贴在最后。
System.out.println("Enter a sequence of integers. Any non-integer to quit");
Scanner scan = new Scanner(System.in);
int min = Integer.MAX_VALUE;
int max = 0;
int count = 0;
int sum = 0;
int oddsCounter = 0;
int evensCounter = 0;
int getInt;
double average = 0;
while (scan.hasNextInt()) {
getInt = scan.nextInt();
if (getInt % 2 == 0) {
evensCounter++;
System.out.println("even: " + evensCounter);
} else {
oddsCounter++;
System.out.println("odd: " + oddsCounter);
}
if (getInt < min) {
min = getInt;
} else if (getInt > max) {
max = getInt;
}
sum += getInt;
System.out.println("sum " + sum);
count++;
System.out.println("count " + count);
average = (double) sum / (count);
System.out.println("average " + average);
}
System.out.println("smallest: " + min);
System.out.println("largest: " + max);
System.out.println("even: " + oddsCounter);
System.out.println("odd: " + evensCounter);
System.out.println("average: " + average);
结果:
Enter a sequence of integers. Any non-integer to quit
9 //input 1
odd: 1
sum 9
count 1
average 9.0
3 //input 2
odd: 2
sum 12
count 2
average 6.0
7 //input 3
odd: 3
sum 19
count 3
average 6.333333333333333
1 //input 4
odd: 4
sum 20
count 4
average 5.0
q //input 5: QUIT
smallest: 1
largest: 7 //This should be 9
even: 0
odd: 4
average: 5.0
结果 2:
Enter a sequence of integers. Any non-integer to quit
q //quit
smallest: 2147483647 //This should be 0
largest: 0
even: 0
odd: 0
average: 0.0
任何帮助,将不胜感激。谢谢!