我有一个应该处理异常的 java gui 应用程序。这是我的程序的总体思路:它应该接受整数类型的输入。输入对话框应导致应捕获的异常并打印消息“错误号码”。但是,我的问题是,如果用户输入空字符串和/或格式错误的数字,我该如何重复 JPanelInput。此外,如果用户选择了 CANCEL 选项,则退出 JOptionPane。
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);
}
更新:
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;
}
}