java - 读取非负整数列表并显示最大整数、最小整数以及所有整数的平均值

标签 java if-statement while-loop

我在计算最大和最小数字时遇到了一些问题...如果我输入的第一个数字比输入的第二个数字大,则不会将第一个数字记录到最大...

看看输出,这将有助于更好地阐述.. 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/

相关文章:

java - 为什么要将新的 ArrayList 分配给 List 变量?

java - 当我们可以使用增强的 for 循环迭代集合时,为什么 Java 仍然保留 Iterator ?

c++ - 程序似乎跳过了 'if' 语句

java - 大米之谜 - 为什么 "If else"语句不能正确循环?

java - Informatica Web Services Hub v9 是否支持 MTOM?

java - 可以使 Maven 构建包含依赖项中的 .class 文件

java - 简单: efficiency of ' if '

vba - 根据 VBA 中的 If 语句插入箭头

php - 使用 while 循环从 mysql 打印整个列

python - 使用循环将对象添加到列表(python)