我有一个任务,需要找到用户输入数字的最小值、最大值和平均值。基本上,他们会输入用空格分隔的正整数,Java会对它们进行遍历并将它们相加。我能够找到总和、平均数和最大整数,但是我无法找到最小值。我认为想要解决这个问题的最好方法是在循环外部将表示最小整数的变量设置为表示最大整数的变量。然后,在循环内部,做类似于以下操作的事情:
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);
}
}
非常感谢您的帮助!