2014-12-07 113 views
-1

我希望我的用户继续输入员工编号,直到用户输入-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 -->"); 
    } 
+2

我没有看到你要的输入'而()'循环内?什么会导致'payData.getOneEmpNum(index)'改变,导致循环中断? – mash 2014-12-07 04:28:31

+0

得到循环内的下一个输入 ** index = myScanner.nextInt(); ** – 2014-12-07 04:34:18

回答

2

您在while循环中没有更新index。在你的循环的末尾添加这一行:

index = myScanner.nextInt(); 

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

+0

谢谢,但现在它不会打印行,如果它的一个无效的数字。它只是结束循环 – jaramore 2014-12-07 04:47:28

+0

是不是整个点...当用户提供-1时结束循环? – 2014-12-07 04:48:50

+0

是的,但它也需要在我的if语句中有效。我也尝试while(payData.getOneEmpNum(index)!= -1 || payData.getOneEmpNum(index)> = 0),它仍然通过循环,如果我输入200.它应该说无效的数字,并再次问这个问题 – jaramore 2014-12-07 04:53:04

0

现在你更新你的代码,看起来像你只需要一个index = myScanner.nextInt(); while循环里面。您目前设置的方式,您会希望在最后的println声明之下。

0

,就应该替换代码的前几行:

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

我不认为这会起作用。在Java中,'x = y'将基于成功返回一个'boolean',而不是操作结果的'integer'?也许我错了。 – mash 2014-12-07 04:53:37

+0

'='是一个赋值运算符,不是比较运算符。 'x == y'将返回我在这里没有使用的布尔值。 @mash – afzalex 2014-12-07 21:27:03

+0

是的,赋值运算符_returns_的一个值。我相信它会返回一个表示成功的'boolean'(这就是C++所做的) – mash 2014-12-08 20:17:13