简体   繁体   中英

Validating user input in JOptionPane.ShowInputDialog

Using JOptionPane.ShowInputDialog, I need to check if the user inputs an int, otherwise, JOptionPane should return an error message and prompt the user to enter the correct data type.

At the same time, if the user clicks to cancel the program should return to the main menu.

String weight = JOptionPane.showInputDialog(null, "Enter your weight in Kg: ");
if(weight == null) {
    menuGUI();
} else {
    setWeight(Integer.valueOf(weight));
}

Any suggestions on how I could do this?

Use while loop

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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM