简体   繁体   English

检查JOptionPane中输入是否为整数

[英]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. 我已经搜索并找到了一些有关使用hasNextInt()方法的帖子,但是这些示例使用了扫描程序,但我不知道如何在JOptionPane中使用它。 When I try askBoxes.hasNextInt() it doesn't work. 当我尝试askBoxes.hasNextInt()时,它不起作用。

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? 我如何将我的else行改写为else if行,以检查输入是否为整数,以便在输入不是整数的情况下也能显示错误消息?

https://www.google.se/#q=java+check+string+is+number 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. 简单来说,您将其解析为Integer,如果失败,您将捕获异常。 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!");
        }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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