【问题标题】:Validating user input in JOptionPane.ShowInputDialog在 JOptionPane.ShowInputDialog 中验证用户输入
【发布时间】:2019-12-06 09:11:08
【问题描述】:
使用 JOptionPane.ShowInputDialog,我需要检查用户是否输入了 int,否则,JOptionPane 应该返回错误消息并提示用户输入正确的数据类型。
同时,如果用户点击取消程序应该返回主菜单。
String weight = JOptionPane.showInputDialog(null, "Enter your weight in Kg: ");
if(weight == null) {
menuGUI();
} else {
setWeight(Integer.valueOf(weight));
}
关于我如何做到这一点的任何建议?
【问题讨论】:
标签:
java
user-interface
joptionpane
【解决方案1】:
使用while循环
Integer w = null;
while (true) {
String weight = JOptionPane.showInputDialog(null, "Enter your weight in Kg: ");
if (weight == null) {
break;
}
try {
w = Integer.parseInt(weight);
break;
} catch (NumberFormatException e) {
JOptionPane.showMessageDialog(null, "Enter a valid integer", "error", JOptionPane.ERROR_MESSAGE);
}
}
if (w == null) { //The user clicked cancel
menuGUI();
} else { //Do what you want with w
}