2014-09-24 42 views
0

比較字符串我試圖過濾用戶的輸入,以確保它的4位的最大值,它不是一個空字符串。無論我留下空白還是輸入數字,!strInput.equals(null)仍然成立。我不正確地比較字符串嗎?在Java中.equals()

我也試過:!strInput.equals(""),strInput != nullstrInput != ""雖然我認爲它應該是.equals(...),因爲我試圖比較值。

 private void updateFast() { 
      String strInput = JOptionPane.showInputDialog(null, "How many?"); 

      if (!strInput.equals(null) && strInput.matches("\\d{0,4}")) 
      { 
       //do something 
      } 
      else 
      { 
       JOptionPane.showMessageDialog(null, "Error. Please Re-enter"); 
       updateFast(); 
      } 

     } 
+0

而不是'strInput.equals(空)'使用'strInput = null' – andrex 2014-09-24 02:44:46

回答

2

更改行:

if (!strInput.equals(null) && strInput.matches("\\d{0,4}")) 

要:

if (strInput != null && strInput.matches("\\d{1,4}")) 

不需要檢查字符串是否爲空,正則表達式會檢查它。

+0

謝謝,其實我剛剛離開它作爲strInput.matches(「\\ d {1, 4}「))。感謝您的幫助,我沒有想到 – 2014-09-24 02:57:52

+0

@OscarF如果strInput爲null,您將得到NullPointerException。在正則表達式匹配之前,你必須檢查null。 – DiogoSantana 2014-09-24 03:11:43

+0

我把整個if else語句放在try catch中。這照顧了NullPointerException。這樣做是錯誤的嗎? – 2014-09-24 03:13:41

1

如果您將輸入值留空,則字符串將爲「」不爲空。您將需要使用!strInput.equals("")來完成您試圖實現的目標。

以防萬一..你可能想.trim()您的字符串。

1

您可以使用strInput != null && !strInput.isEmpty()

0

你可以這樣做:!

strInput = NULL & & strInput.trim()長()> 0

0

試試這個

if (!strInput.isEmpty() ... 
if (strInput != null && strInput.length() > 0 ... 

我希望這是有幫助的。

0

你比較錯了。

當你傳遞一個對象來String.equals(對象o)的事情會做一個檢查,如果傳遞的參數是String.class的一個實例。由於您傳遞null,它將始終返回false。

您應該檢查,看看你的字符串爲null,然後,如果它是空的。 String.class確實有這個方法。

所以:!

if(strInput != null && !strInput.isEmpty() && strInput.matches("\\d{0,4}")) { 
    // do something... 
} else { 
    JOptionPane.showMessageDialog(null, "Error. Please Re-enter"); 
    updateFast(); 
}