简体   繁体   中英

Check if input is an integer in JOptionPane

JFrame frame2 = new JFrame("Boxes");
String askBoxes= JOptionPane.showInputDialog(frame2, 
    "How many boxes?",
    "# of boxes",
    JOptionPane.QUESTION_MESSAGE);

if(askBoxes == null) {
    JOptionPane.showMessageDialog(null, "User pressed cancel, exiting program now!");
    System.exit(0);
} else {
    numBoxes= Integer.parseInt(askBoxes);
}

I am supposed to create a program that asks for inputs as integers but is also able to return an error message if the user inputs something other than an integer. I've searched and found some posts about using the hasNextInt() method but those examples used scanner and I can't figure out how to use it with JOptionPane. When I try askBoxes.hasNextInt() it doesn't work.

How can I rewrite my else line into an else if line that checks if the input was an integer so that I would also be able to show an error message if the input was anything other than an integer?

https://www.google.se/#q=java+check+string+is+number

Simply, you fro to parse it into a Integer, and if it fails, you will catch an exception. That way you know if it's a integer or not.

}else{ 

        try { 
           numBoxes= Integer.parseInt(askBoxes);

        } catch(NumberFormatException e) { 
          JOptionPane.showMessageDialog(null, "Value must be an integer!");
        }
}

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