2013-11-14 123 views
0

我試圖讓用戶輸入一個整數到文本字段。當用戶輸入非整數時,try catch塊應該處理異常。應該出現一個消息對話框,告訴用戶他們應該輸入其他內容,但我似乎無法做到這一點。處理異常並獲取消息對話框以顯示

class ButtonListener implements ActionListener 
    { 
     public void actionPerformed (ActionEvent event) 
     { 
      try 
      { 
       String r = radiusField.getText(); 
       int radius = Integer.parseInt (r); 
       double area = Math.PI * radius * radius; 
       areaArea.setText ("" + area); 
      } 

      catch (InputMismatchException ex) 
      { 
       JOptionPane.showMessageDialog (null, "Error in number format: Reenter the number"); 
       radiusField.setText (""); 
       areaArea.setText (""); 
      } 
     } 
    } 

回答

0

使用NumberFormatException而不是InputMismatchException

catch (NumberFormatException ex) { 
    /* ... */ 
}