2014-02-18 134 views
0
===== CS302 TOOL BOX ===== 
T > COIN TOSS SIMULATOR 
G > GRADE ESTIMATOR 
C > COLOR CHALLENGE 
Q > QUIT 
Type code letter for your choices: h 
Invalid selection. Please try agian: 
t 
Invalid selection. Please try agian: 
T 

^这就是我在运行程序并给出错误的猜测时所得到的结果。该循环用于验证用户输入,因此它完全失败。关于我做错了什么想法?谢谢你的时间!输入验证(do-while循环)出现故障

} 

    System.out.println("===== CS302 TOOL BOX ====="); 
    System.out.println("T > COIN TOSS SIMULATOR"); 
    System.out.println("G > GRADE ESTIMATOR"); 
    System.out.println("C > COLOR CHALLENGE"); 
    System.out.println("Q > QUIT"); 
    System.out.print("Type code letter for your choices: "); 
    boolean code_letter; 
    String code_choice = scanner.next(); 
    do { 
     if (code_choice.toUpperCase().equals("Q") 
       || (code_choice.toUpperCase()).equals("C") 
       || (code_choice.toUpperCase()).equals("G") 
       || (code_choice.toUpperCase()).equals("T")) { 
      code_letter = true; 
     } 

     else { 
      System.out.println("Invalid selection. Please try agian: "); 
      code_letter = false; 
      scanner.next(); 
     } 
    } while (!(code_letter)); 

    { 

     System.out.println("you did it?"); 
    } 

} 
} 
+0

请不要在获得答案后用垃圾文本替换您的问题。留下问题让未来的读者学习。 –

+0

如果答案对您有帮助,点击旁边的复选标记以接受答案是礼貌的。 http://stackoverflow.com/help/accepted-answer –

回答

0

只是尝试..

把你

scanner.next() 

之前,如果去掉花括号包围

System.out.println("you did it?"); 

最后你而改变......它来..

while(code_letter != true); 
0

我假设扫描仪(小写字母S)是扫描仪对象?请在下次包含所有相关代码,否则调试问题非常困难。

您遇到的主要问题是在else条件的行中。 scanner.next()不会执行任何操作。你需要这样做:

else { 
    System.out.println("Invalid selection. Please try agian: "); 
    code_letter = false; 
    code_choice = scanner.next(); // This needs to be modified 
} 

这应该让它工作。

1

初始化变量code_choicedo-while循环内,否则变量将不会重新初始化,条件测试前循环的每次迭代。

String code_choice = scanner.next(); 

这样

//declared it outside to take care of the scope 
String code_choice = null; 
    do { 
     //initialize it every time before you perform the conditional test. 
     //This increases the readability! 
     code_choice = scanner.next(); 
     if (code_choice.toUpperCase().equals("Q") 
       || (code_choice.toUpperCase()).equals("C") 
       || (code_choice.toUpperCase()).equals("G") 
       || (code_choice.toUpperCase()).equals("T")) { 
      code_letter = true; 
     } 

     else { 
      System.out.println("Invalid selection. Please try agian: "); 
      code_letter = false; 
     } 
    } while (!(code_letter)); 

希望这有助于!