【问题标题】: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
    }
    

    【讨论】:

      猜你喜欢
      • 2016-03-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-09-11
      相关资源
      最近更新 更多