2013-08-23 86 views
0

我有一個java gui應用程序應該處理異常。這裏是我的程序的總體思路:它應該接受整數類型的輸入。輸入對話框應該會引起一個應該被捕獲的異常並打印「不良號碼」消息。 但是,我的問題是,如果用戶輸入空字符串和/或格式不正確的數字,我怎麼能重複JPanelInput。另外,如果用戶選擇取消選項,請跳出JOptionPane。多次嘗試/趕上重複JPaneInput

String strIndex = this.showInputDialog(message, "Remove at index"); 
int index; 

// while strIndex is empty && str is not type integer 
while (strIndex.isEmpty()) { 
     strIndex = this.showInputDialog(message, "Remove at index"); 
     try { 
      if (strIndex.isEmpty()) { 

      } 
     } catch (NullPointerException np) { 
      this.showErrorMessage("Empty field."); 
     } 


     try { 
      index = Integer.parseInt(strIndex); 
     } catch (NumberFormatException ne) { 
      this.showErrorMessage("You need to enter a number."); 
     } 
} 


    void showErrorMessage(String errorMessage) { 
     JOptionPane.showMessageDialog(null, errorMessage, "Error Message", JOptionPane.ERROR_MESSAGE); 
    } 

    String showInputDialog(String message, String title) { 
     return JOptionPane.showInputDialog(null, message, title, JOptionPane.QUESTION_MESSAGE); 
    } 

UPDATE:

String strIndex; 
      int index; 
      boolean isOpen = true; 

      while (isOpen) { 
       strIndex = view.displayInputDialog(message, "Remove at index"); 
       if (strIndex != null) { 
        try { 
         index = Integer.parseInt(strIndex); 
         isOpen = false; 
        } catch (NumberFormatException ne) { 
         view.displayErrorMessage("You need to enter a number."); 
        } 
       } else { 
        isOpen = false; 
       } 
      } 

回答

2

showInputDialog()返回NULL,如果用戶選擇取消。所以這裏是基本的算法。我會讓你把它翻譯成Java:

boolean continue = true 
while (continue) { 
    show input dialog and store result in inputString variable 
    if (inputString != null) { // user didn't choose to cancel 
     try { 
      int input = parse inputString as int; 
      continue = false; // something valid has been entered, so we stop asking 
      do something with the input 
     } 
     catch (invalid number exception) { 
      show error 
     } 
    } 
    else { // user chose to cancel 
     continue = false; // stop asking 
    } 
}