我在计算最大和最小数字时遇到了一些问题...如果我输入的第一个数字比输入的第二个数字大,则不会将第一个数字记录到最大...
看看输出,这将有助于更好地阐述.. Calculation Error.. & 1st input problem.. 代码如下!
public static void main(String[] args) {
int smallest = Integer.MAX_VALUE;
int largest = 0;
int number;
double totalAvg = 0;
double totalSum = 0;
int count = 0;
Scanner kb = new Scanner(System.in);
System.out.println("Enter few integers (Enter negative numbers to end input) :");
while (true) { //LOOP till user enter "-1"
number = kb.nextInt();
//Condition for the loop to break
if (number <= -1) {
System.out.println("End Of Input");
break;
} else {
count = count + 1;
}
if (number < smallest) { //Problem 1 : If 1st input num is bigger than 2nd input num,
smallest = number; // largest num will not be recorded..
} else {
largest = number;
}
totalSum = totalSum + number;
totalAvg = (totalSum / count);
}
System.out.println("The smallest number you have entered is : " + smallest);
System.out.println("The largest number you have entered is : " + largest);
System.out.println("The total sum is : " + totalSum);
System.out.println("The total average is : " + totalAvg);
System.out.println("Count : " + count);
} // PSVM
最佳答案
如果您使用的是 Java 8,则可以构建 IntStream
,并使用 IntSummaryStatistics
自动提取这些数字。可以从Oracle官方文档here找到。
这里是实现这一点的代码:
List<Integer> input = new ArrayList<>();
while (true) { // LOOP till user enter "-1"
number = kb.nextInt();
// Condition for the loop to break
if (number <= -1) {
System.out.println("End Of Input");
break;
} else {
input.add(number);
}
}
IntSummaryStatistics z = input.stream() // gives Stream<Integer>
.mapToInt(Integer::intValue) // gives IntStream
.summaryStatistics(); // gives you the IntSummaryStatistics
System.out.println(z);
如果您输入8 3 7
,输出将为:
IntSummaryStatistics{count=3, sum=18, min=3, average=6.000000, max=8}
希望对您有帮助!
关于java - 读取非负整数列表并显示最大整数、最小整数以及所有整数的平均值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37760980/