java - 根据输入找到最小的整数

标签 java

我有一个作业要查找用户输入的数字的最小值、最大值和平均值。基本上,他们输入正整数,用空格分隔,然后 Java 滚动浏览它们并将它们相加。我能够找到总和、平均值和最大整数,但是,我找不到最小的整数。我认为解决这个问题的最好方法是将表示最小 int 的变量设置为等于表示循环外最大 int 的变量。然后,在循环中,执行如下操作:

        if(getInt < min)
        {
            min = getInt;
        }

其中 getInt 是用户输入的值,min 是最小整数值。不过,每次我运行它时,min 都会返回 0。

这是我的完整代码:

import java.util.Scanner;

public class exc5
{
    public static void main (String[] args)
    {  
        System.out.println("Write a list of nonnegative integers, each seperated by a space. To signal the end of the list, write a negative integer. The negative integer will not be counted");
        Scanner keyboard = new Scanner (System.in);
        keyboard.useDelimiter(" |\n");

        int count = 0;
        int sum = 0;
        int max = 0;
        int min = max;
        double average = 0;

        boolean notNull = true;

        while(notNull == true)
        {
            int getInt = keyboard.nextInt();

            if(getInt < 0)
            {
                notNull = false;
            }  
            else
            {          
                if(getInt > max)
                {
                    max = getInt;
                }

                if(getInt < min)
                {
                    min = getInt;
                }

                sum += getInt;
                count++;
                average = (sum)/(count);
            }
        }

        System.out.println("Sum = " + sum);
        System.out.println("Average = " + average);
        System.out.println("Max = " + max);
        System.out.println("Minimum = " + min);
    }

}

感谢任何帮助!

最佳答案

您应该首先设置 minInteger.MAX_VALUE , 和 maxInteger.MIN_VALUE .

关于java - 根据输入找到最小的整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9367554/

相关文章:

java - 在浏览器上定期显示消息

java - 在 Java 中对项目进行分组

java - xercesImpl.jar 在类路径上时 NetBeans Web 服务客户端出现问题

java - 制作 JPA 实体的保护性副本

java - 如何停止我的服务?

java - 在方法中检查可空变量是否为空但未识别

Java StringBuffer 问题

java 二维图形库

java - 银行账户分配

java - Android - JSONArray 上的 toString 使用双引号和反斜杠使 json 无效