gpt4 book ai didi

java - 验证 JOptionPane.ShowInputDialog 中的用户输入

转载 作者:行者123 更新时间:2023-12-02 09:13:28 25 4
gpt4 key购买 nike

使用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
}

关于java - 验证 JOptionPane.ShowInputDialog 中的用户输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59210035/

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