2013-10-20 91 views
0

我可能只是很累。但不管我嘗試過的代碼總是執行。 如何獲取下面的代碼,只有在字符串包含字符時才執行?JOptionPane.showInputDialog問題

String input = JOptionPane.showInputDialog(this, "Enter your budget!", "Set Budget", 1); 

    //If the input isnt empty 
    System.out.println(input); 
    if(!"".equals(input) || input != null){ 
     try{ 
      budgetValue = Double.parseDouble(input); 
      budgetIn.setText(String.format("$%1$,.2f", budgetValue)); 
       setDifference(); 
     } 
     catch(Exception ex){ 
      JOptionPane.showMessageDialog(this, "Unable to set budget!\n" + 
               "Please enter a usable value!", "Sorry!", 0); 
     } 
    } 
+3

您應該在AND條件中使用AND(&&)運算符而不是OR(||)。 – ntalbs

+0

還:那system.out.println()是我看到的字符串確實是null –

+0

哦。謝謝..我一直在用Java編程一段時間,從來沒有遇到過這個問題|| ..你能解釋爲什麼請嗎? –

回答

1

你可能會考慮嘗試類似...

if(input != null && !input.trim().isEmpty()){...} 

這應確保if語句被執行,只要內容不爲空

要小心的是,這種修剪input的空格,所以如果你只是輸入空格並按輸入,它將跳過if聲明;)

更新

要過濾inputString,以確保它包含唯一有效的數值,你可以使用String#match和正則表達式...

if (input != null && input.matches("^\\d+(\\.(\\d+)?)?$")) {...} 

這應該確保if聲明只有在輸入數值時才執行。小數點(小數點)是可選的

+0

謝謝!無論如何,如果用戶輸入除double以外的內容,則會引發異常。 –

+0

我以爲你想要'如果'語句執行,如果用戶輸入*「如果字符串包含字符?」*;) – MadProgrammer

相關問題