我正在使用JOptionPane
框对程序进行输入验证。每次用户输入非双重语句时,我都会尝试在错误消息后重复输入框。我该怎么做?
try {
lengthResult = Double.parseDouble(JOptionPane.showInputDialog("What is the length of your garage in square feet?"));
}
catch (NumberFormatException e) {
JOptionPane.showMessageDialog(null, "Please enter a number in digit format.","Inane error",JOptionPane.ERROR_MESSAGE);
}
答案 0 :(得分:0)
如果您想重复此消息框,直到用户输入有效内容,我会这样:
Double lengthResult = null; //Init to null, which is invalid
String title = "Please anter a number";
int initialType = JOptionPane.QUESTION_MESSAGE;
do {
try {
lengthResult = Double.parseDouble(
JOptionPane.showInputDialog(null,
"What is the length of your garage in square feet?",
title, initialType));
} catch (NumberFormatException e) {
initialType = JOptionPane.ERROR_MESSAGE;
title = "Error: Please enter a number!";
}
} while(lengthResult == null); //Iterate as long as no valid input found
请注意,此检查依赖于lengthResult是Double类型的Object,而不是基本类型double。对于原始的双倍,你需要一些额外的标志,因为你不能用这种方式检查lengthResult值。