java - 在 JOptionPane.ShowInputDialog 中验证用户输入
问题描述
使用 JOptionPane.ShowInputDialog,我需要检查用户是否输入了 int,否则,JOptionPane 应该返回错误消息并提示用户输入正确的数据类型。
同时,如果用户点击取消程序应该返回主菜单。
String weight = JOptionPane.showInputDialog(null, "Enter your weight in Kg: ");
if(weight == null) {
menuGUI();
} else {
setWeight(Integer.valueOf(weight));
}
关于我如何做到这一点的任何建议?
解决方案
使用 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
}
推荐阅读
- string - 批处理文件 - 名称
- javascript - 无法将属性设置为 null
- python - 连接之前的输入数组必须具有相同的维数
- c# - 如何引用接口属性
- regex - 当单词不是(某些单词)时匹配 Word()
- scala - 在使用 Futures、akka 流和 akka 演员的并发环境中,与非线程安全服务集成,同时保持背压
- algorithm - 流/图:最早日期的城市将被连接
- python - 如何构建和安装 OpenCV 4.0?
- regex - 正则表达式验证带有数字和字母的字符串
- webdriver-io - WebdriverIO:elementIdHtml 的等价物是什么?