2017-10-05 39 views
-1

任何人都可以解釋爲什麼while循環問whatNight兩次?以及如何重新提示無效的用戶輸入,如果用戶輸入的東西比「R」或「C」我如何報告無效的用戶輸入並恢復該值?

for(int x = 1; x <= inputInt; x++) { 
    char whatNight = JOptionPane.showInputDialog("Enter c or r for what type of night").charAt(0); 
    boolean pleasework = whatNight == 'c' || whatNight == 'C'; 
    boolean imbeggingu = whatNight == 'r' || whatNight == 'R'; 
    boolean doesNotWork = whatNight != 'c' && whatNight != 'C' && whatNight != 'r' && whatNight != 'R'; 

    //why does the while loop ask twice even if u enter c or r? 
    while(pleasework || imbeggingu || doesNotWork) { 

     if(doesNotWork) 
      JOptionPane.showMessageDialog(null, "INvalid letter"); 
      whatNight = JOptionPane.showInputDialog("Enter c or r for what type of night").charAt(0); 
     //reprompt not storing in whatNight variable :/ 

      if(pleasework) 
      JOptionPane.showMessageDialog(null, "You entered c for carnight"); 

      else if(imbeggingu) 
      JOptionPane.showMessageDialog(null, "You entered r for regular night"); 
      break; 
    } 

回答

0

要回答你的問題,我建議你調試你的價值觀作爲第一步,例如

System.out.println(pleasework); 
其他

你的概念邏輯是相當不錯的,你應該重新思考你想如何處理這個問題。例如,當你的輸入不是C或R時,你需要一個新的輸入,但你不要根據它設置任何布爾值。

這應該工作!

for(int x = 1; x <= inputInt; x++) { 
    char whatNight = JOptionPane.showInputDialog("Enter c or r for what type of night").charAt(0); 
    whatNight = checkInput(whatNight); 
    boolean nightC = whatNight == 'c' || whatNight == 'C'; 
    boolean nightR = whatNight == 'r' || whatNight == 'R'; 

    if(nightC) { 
     JOptionPane.showMessageDialog(null, "You entered c for carnight"); 
    } else if(nightR) { 
     JOptionPane.showMessageDialog(null, "You entered r for regular night"); 
    } 
} 

--------------------------------------------------------------------- 

private char checkInput(char input) { 
    if(input == 'c' || input == 'C' || input == 'r' || input == 'R') { 
     return input; 
    } 
    char whatNight = JOptionPane.showInputDialog("You entered a wrong letter, enter either c or r for what type of night it was").charAt(0); 
    return checkInput(whatNight); 
} 

如果你不明白的東西讓我知道,我會解釋!

相關問題