2013-08-23 2 views
0

예외를 처리하기로되어있는 java gui 앱이 있습니다. 내 프로그램의 전반적인 개념은 다음과 같습니다. 정수형 입력을 허용해야합니다. 입력 대화 상자에서 예외가 발생하여 "잘못된 번호"라는 메시지가 인쇄됩니다. 그러나 문제는, 사용자가 빈 문자열 및/또는 잘못된 형식 번호를 입력하면 JPanelInput을 반복하는 방법입니다. 또, 유저가 CANCEL 옵션을 선택했을 경우, 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를 돌려줍니다. 여기에 기본적인 알고리즘이 있습니다. 자바로 번역 해 드리겠습니다 :

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 
    } 
}