尝试编写一个在用户输入负值时停止的程序。然而,即使用户输入负值,循环仍然继续运行。不知道为什么。请帮忙!
int input, smallest = 0, largest=0, total = 0, count = 1;
double avg;
System.out.print("Enter a number: ");
input = keyboard.nextInt();
while(input > 0)
{
System.out.print("Enter a number: ");
largest = keyboard.nextInt();
count++;
if (input > largest)
{
largest = input;
}
else
{
smallest = input;
}
total = total + largest + smallest;
}
avg = total / count;
System.out.println("Largest number is: " + largest);
System.out.println("Smallest number is: " + smallest);
System.out.printf("Average number is: %.2f \n", avg);
最佳答案
您没有更新循环内 input
的值。
你需要做这样的事情:
while(input > 0)
{
System.out.print("Enter a number: ");
input = keyboard.nextInt(); //Update the input value for this iteration.
largest = input;
...
}
关于java - 我的 Java Sentinel-Controlled 循环不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39182578/