Check if input is an integer in JOptionPane

让人想犯罪 __ 提交于 2019-12-13 08:19:26

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!