2014-11-01 35 views
0

我正在尋找有關如何捕獲用戶輸入的無效字符串的異常。我有一個例外的整數輸入以下代碼:Java捕獲異常 - 空字符串

  try { 
      price = Integer.parseInt(priceField.getText()); 
      } 
      catch (NumberFormatException exception) { 
      System.out.println("price error"); 
      priceField.setText(""); 
      break; 

但我不知道字符串特定異常,輸入是一個簡單的JTextBox所以只能輸入不正確,我能想到的是,如果用戶什麼都不輸入,這正是我想要捕捉的。

回答

6
if (textField.getText().isEmpty()) 

是你所需要的。

或許

if (textField.getText().trim().isEmpty()) 

,如果你也想測試空白輸入,只包含空格/製表符。

您通常不會使用異常來測試值。測試字符串是否代表整數是規則的例外,因爲String中沒有可用的isInt()方法。

0

你可以這樣做

if (priceField.getText().isEmpty()) 
    throw new Exception("priceField is not entered."); 
1

您可以檢查是否priceField包含字符串使用此:

JTextField priceField; 
int price; 
try { 
// Check whether priceField.getText()'s length equals 0 
if(priceField.getText().getLength()==0) { 
    throw new Exception(); 
} 
// If not, check if it is a number and if so set price 
price = Integer.parseInt(priceField.getText()); 
} catch(Exception e) { 
// Either priceField's value's length equals 0 or 
// priceField's value is not a number 

// Output error, reset priceField and break the code 
System.err.println("Price error, is the field a number and not empty?"); 
priceField.setText(""); 
break; 
} 

當if語句爲真(如果priceField.getText()長度爲0)拋出異常,這將觸發catch-block,發出錯誤,重置priceFieldbreak的代碼。

如果if語句雖然爲假(如果priceField.getText()的長度大於或小於0),它將檢查priceField.getText()是否是一個數字,如果是,則將price設置爲該值。如果它不是一個數字,則拋出一個NumberFormatException異常,這將觸發catch-block等。

讓我知道它是否有效。

編碼愉快:) -Charlie

如果你想在Java虛擬機的正常運行期間拋出你的異常
+4

這是如此醜陋... – slnowak 2014-11-01 19:37:35

1

,那麼你可以使用這個

if (priceField.getText().isEmpty()) 
    throw new RunTimeException("priceField is not entered.");