2013-08-23 5 views
0

У меня есть приложение java gui, которое должно обрабатывать исключение. Вот общая идея моей программы: она должна принимать ввод целочисленного типа. Диалог ввода должен вызвать исключение, которое должно быть уловлено и напечатать сообщение «плохой номер». Однако моя проблема в том, как я могу повторить JPanelInput, если пользователь вводит пустую строку и/или номер плохого формата. Кроме того, если пользователь выбрал вариант CANCEL, выйдите из JOptionPane.Несколько Try/Catch with Repeating 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() возвращает нулевое значение, если пользователь выбрал для отмены. Итак, вот основной алгоритм. Я позволю вам перевести его на 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 
    } 
}