gpt4 book ai didi

java - 重复 JPaneInput 的多次 Try/Catch

转载 作者:行者123 更新时间:2023-12-02 06:47:50 27 4
gpt4 key购买 nike

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

最佳答案

如果用户选择取消,

showInputDialog() 将返回 null。这是基本算法。我会让你把它翻译成 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
}
}

关于java - 重复 JPaneInput 的多次 Try/Catch,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18402600/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com