我的Java Sentinel-Controlled循环不起作用

时间:2016-08-27 15:07:58

标签: java loops

尝试编写一个程序,当用户输入负值时将停止该程序。然而,即使用户输入负值,循环仍然继续运行。不知道为什么。请帮忙!

    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);

1 个答案:

答案 0 :(得分:2)

您没有在循环中更新input的值。

你需要做这样的事情:

while(input > 0)
{

    System.out.print("Enter a number: ");

    input = keyboard.nextInt(); //Update the input value for this iteration.
    largest = input;
    ...
}