不断要求用户输入数据,陷入无限循环

时间:2014-12-07 04:26:28

标签: java while-loop user-input

我希望我的用户继续输入员工编号,直到用户输入-1,这会停止循环。但是我的代码不断打印输入的数字并且不会再问另一个问题。

    System.out.println("Which employee number do you want to see -->");
    index = myScanner.nextInt();

    while (payData.getOneEmpNum(index) != -1)
    {
        if (payData.getOneEmpNum(index) >= 0)
        {   
            System.out.printf("Sequential found employee #%d ",payData.getOneEmpNum(index));
            System.out.printf("and the pay rate is $%.2f.\n ",  payData.getPayRate(index));

            System.out.printf("Binary found employee #%d ",payData.getOneEmpNum(index));
            System.out.printf("and the pay rate is $%.2f.\n ",  payData.getPayRate(index));
        }
        else
        {
            System.out.println("Invalid employee number!");
        }

        System.out.println("Which employee number do you want to see -->");
    }

3 个答案:

答案 0 :(得分:2)

您没有在while循环中更新index。在循环结束时添加此行:

index = myScanner.nextInt();
System.out.println("Which employee number do you want to see -->");

之后

答案 1 :(得分:0)

现在您已经更新了代码,看起来您只需要在while循环中使用index = myScanner.nextInt();。您目前设置的方式是,您希望它位于最后println语句的下方。

答案 2 :(得分:0)

您应该替换代码的前几行:

while ((index = myScanner.nextInt()) != -1)
{
    if (payData.getOneEmpNum(index) >= 0)
    {