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