2012-10-27 222 views
0

是否可以檢查輸入字符串是否爲NumberFormatException""是否可以檢查java.lang.NumberFormatException?

我試着寫我的程序,這樣,如果用戶沒有把任何價值觀的錯誤信息會出來,而不是NumberFormatException異常的:

if(pasientNavnFelt.getText() == null || pasientNrFeIt.getText() == null) 
{ 
    utskriftsområde.setText("ERROR, insert values"); 
} 

if(pasientNavnFelt.getText() != null || pasientNrFeIt.getText() != null) 
{ 
    // rest of code here if the program had values in it 
} 

if(pasientNavnFelt.getText() == "" || pasientNrFeIt.getText() == "") 
{ 
    utskriftsområde.setText("ERROR, insert values"); 
} 

if(pasientNavnFelt.getText() != "" || pasientNrFeIt.getText() != "") 
{ 
    // rest of code here if the program had values in it 
} 

我也試過無效

我仍然得到:

Exception in thread "AWT-EventQueue-0" java.lang.NumberFormatException: For input string: ""

該程序工作正常,如果它有值。

+2

當然,趕上例外。 –

+1

合併一個try-catch塊來處理異常。 –

回答

2

決不==比較字符串。 ==檢查兩個對象是否相同,而不是兩個對象具有相同的字符。使用equals()來比較字符串。

這就是說,要驗證一個字符串是一個有效的整數,你確實需要捕獲異常:

try { 
    int i = Integer.parseInt(s); 
    // s is a valid integer 
} 
catch (NumberFormatException e) { 
    // s is not a valid integer 
} 

這是基本的Java的東西。閱讀Java tutorial over exceptions

+0

完美工作,thx =) – Madde

1

嘗試:

if(pasientNavnFelt.isEmpty() || pasientNrFeIt.isEmpty()) { 
    utskriftsområde.setText("ERROR, insert values"); 
} 
else { 
    ... 
} 
+0

值得注意的是OP的原始問題之一是使用'=='來表示字符串相等,而不是'.equals(...)'。 –

0

你的第二個,如果條件是錯誤的。你試圖說,如果有一個空,錯誤,否則做一些事情。你在說如果有一個空錯誤,那麼如果它們中的任何一個不爲空,就剩下其餘的。這兩個字符的變化是改變了第二個「||」到「& &」。但你可能想要的其實是:

if(pasientNavnFelt.getText() == null || pasientNrFeIt.getText() == null) 
     { 
      utskriftsområde.setText("ERROR, insert values"); 
     } 
    else 
     { <rest of code here if the program had values in it>}