检查JOptionPane中输入是否为整数 [英] Check if input is an integer in JOptionPane

查看:105
本文介绍了检查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);
}

我应该创建一个要求输入为整数的程序,但是如果用户输入的不是整数,也能够返回错误消息.我已经搜索并找到了一些有关使用hasNextInt()方法的帖子,但是这些示例使用了扫描程序,但我不知道如何在JOptionPane中使用它.当我尝试askBoxes.hasNextInt()时,它不起作用.

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.

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

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

简单来说,您将其解析为Integer,如果失败,您将捕获异常.这样,您就知道它是否是整数.

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!");
        }
}

这篇关于检查JOptionPane中输入是否为整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆