2013-05-12 143 views
0

我在這裏我的代碼,我試圖檢查用戶輸入Y或N來獲取switch語句,但是即使我寫Y或N它給了我錯誤消息,我是什麼做錯了?在此先感謝驗證用戶輸入的字母

+0

'響應!= 「Y」 ||迴應!=「N」 - 錯誤。 – Lion 2013-05-12 02:36:21

+0

它呢?我刪除它嗎?還是以不同的方式寫它? – 2013-05-12 02:37:39

+0

謝謝Reimeus((:: – 2013-05-12 02:38:15

回答

0

您應該使用equals()來比較字符串。

0

上面的回答是正確的 - 但你可能想要最小化字符串比較你的主要功能(這很快就會變得很難維護,你有一個完美的機會來封裝用戶輸入作爲布爾)

像這樣的東西可以幫助你從長遠來看

public void anotherAction() throws IOException 
    { 
     System.out.println(); 
     System.out.println("Would you like to perform an additional action? 'Y' or 'N'"); 
     if (getAction()) 
     { 
      cc.getCommand(this.makeOption()); 
     } 
     else { 
      System.out.println("Exiting System..."); 
     } 
    } 

    private bool getAction() 
    { 
     while(true) 
     { 
      System.out.println("Enter either 'Y' or 'N'"); 
      String response =reader.nextLine().toUpperCase(); 
      if (response.equals("Y")) { 
       return true; 
      } 
      else if (response.Equals("N")) { 
       return false; 
      } 
      else { 
       System.out.println("Wrong input, please try again..."); 
      } 
     } 
    } 
+0

我想我通過查看代碼來做到了複雜化,但是我沒有使用IF語句驗證輸入時的良好體驗 – 2013-05-12 03:15:35