问题
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?
回答1:
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!");
}
}
来源:https://stackoverflow.com/questions/23598253/check-if-input-is-an-integer-in-joptionpane