我有一个作业要查找用户输入的数字的最小值、最大值和平均值。基本上,他们输入正整数,用空格分隔,然后 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);
}
}
感谢任何帮助!
最佳答案
您应该首先设置 min
至 Integer.MAX_VALUE
, 和 max
至 Integer.MIN_VALUE
.
关于java - 根据输入找到最小的整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9367554/