验证 JOptionPane.ShowInputDialog 中的用户输入

Validating user input in JOptionPane.ShowInputDialog

使用JOptionPane.ShowInputDialog,我需要检查用户是否输入了int,否则,JOptionPane 应该return 一条错误消息并提示用户输入正确的数据类型。

同时,如果用户点击取消程序应该return到主菜单。

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
}