2017-03-01 75 views
0

Java新手,所以任何幫助將不勝感激。在JTextField中有一個數據驗證的小問題。 要求用戶輸入他們的年齡,他們是否吸菸,以及他們是否超重。 驗證吸菸和體重的效果很好,我設定的年齡限制也是如此。JTextField數據驗證

但是,如果我在ageField JTextField中輸入一個字母,它似乎會卡住並且不會打印其他驗證錯誤。 (例如,它會正確打印「年齡必須是整數」,但是如果我也在smokesField中鍵入「h」,「煙霧輸入應該是Y,y,N或n」將不會被打印)。

對不起,這是一個漫長而臃​​腫的解釋!

反正這裏是我遇到,三江源困難代碼:

public void actionPerformed(ActionEvent e) 
{ 
String ageBox = ageField.getText(); 
int age = 0; 

if (e.getSource() == reportButton) 
{ 
    if (ageBox.length() != 0) 
     { 
      try 
      { 
      age = Integer.parseInt(ageBox); 
      } 
      catch (NumberFormatException nfe) 
      { 
      log.append("\nError reports\n==========\n");  
      log.append("Age must be an Integer\n"); 
      ageField.requestFocus(); 
      }   
     } 
    if (Integer.parseInt(ageBox) < 0 || Integer.parseInt(ageBox) > 116) 
    { 
     log.append("\nError reports\n==========\n"); 
     log.append("Age must be in the range of 0-116\n"); 
     ageField.requestFocus(); 
    } 
    if (!smokesField.getText().equalsIgnoreCase("Y") && !smokesField.getText().equalsIgnoreCase("N")) 
    { 
     log.append("\nError reports\n==========\n"); 
     log.append("Smoke input should be Y, y, N or n\n"); 
     smokesField.requestFocus(); 
    } 
    if (!overweightField.getText().equalsIgnoreCase("Y") && !overweightField.getText().equalsIgnoreCase("N")) 
    { 
     log.append("\nError reports\n==========\n"); 
     log.append("Over Weight input should be Y, y, N or n\n"); 
     smokesField.requestFocus(); 
    } 
    } 
+0

第二個'Integer.parseInt(ageBox)'會拋出異常 – Jerry06

回答

0

從你描述的情況,很可能是線路

if (Integer.parseInt(ageBox) < 0 || Integer.parseInt(ageBox) > 116) 
{ 
... 

拋出未處理NumberFormatException的,因爲你已經在ageBox中輸入了一封信。您的try/catch處理函數捕獲異常後第一次得到「Age必須是整數」的正確輸出,但第二次出現沒有這種處理。

爲了解決這個問題,我想簡單地移動特定的if語句try塊內,像這樣:

try 
    { 
     if (Integer.parseInt(ageBox) < 0 || Integer.parseInt(ageBox) > 116) 
     { 
      log.append("\nError reports\n==========\n"); 
      log.append("Age must be in the range of 0-116\n"); 
      ageField.requestFocus(); 
     } 
    } 
    catch (NumberFormatException nfe) 
    ... 

這樣,你還是會得到的輸出「年齡必須爲整數,」如果ageBox有一個無效的條目,其他一切都應該運行良好。

+0

Thankyou的快速回復。 試過你的建議,現在完美地工作。 – RiceCrispy

+0

@RiceCrispy沒問題,我很高興你發現它有幫助! –