2014-02-18 58 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)); 

希望這有助於!