У меня есть приложение 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;
}
}