Java 如何验证输入的文本是否为数字?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3412135/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 23:04:15  来源:igfitidea点击:

How to validate if Text entered is a numeric number?

javaswingprogramming-languagesvalidationjoptionpane

提问by JavaNoob

I have a calculation application which I need to validate the fields to check if the values entered are numeric numbers and not alphanumeric. I have some ideas about the codes.
Please guide me if I have done anything wrong or seem noob as this is my first time trying out Swing.

我有一个计算应用程序,我需要验证字段以检查输入的值是否是数字而不是字母数字。我对代码有一些想法。
如果我做错了什么或看起来像菜鸟,请指导我,因为这是我第一次尝试 Swing。

private void jTextField1ActionPerformed(java.awt.event.ActionEvent evt) {
    String text1 = jTextField1.getText();            // TODO add your handling code here:
}

private void jTextField2ActionPerformed(java.awt.event.ActionEvent evt) {
    String text2 = jTextField2.getText();        // TODO add your handling code here:
}

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
    if (text1 and text2 != <numeric number>){
        JOptionPane.showConfirmDialog(null, "Please enter numbers only", "naughty", JOptionPane.CANCEL_OPTION);
    }
    // First we define float variables.
    float num1, num2, result;
    // We have to parse the text to a type float.
    num1 = Float.parseFloat(jTextField1.getText());
    num2 = Float.parseFloat(jTextField2.getText());
    // Now we can perform the addition.
    result = num1+num2;
    // We will now pass the value of result to jTextField3.
    // At the same time, we are going to
    // change the value of result from a float to a string.
    jTextField3.setText(String.valueOf(result));
    // TODO add your handling code here:
}

Please do help. By the way why does my NetBeans keep informing me that it does not recognize the "JOptionPane" Command?

请帮忙。顺便说一下,为什么我的 NetBeans 一直通知我它无法识别“JOptionPane”命令?

采纳答案by samitgaur

Float.parseFloat()will throw a NumberFormatExceptionif the Stringisn't numeric and cannot be parsed into a Float. You can add a try-catchblock to check for this condition:

Float.parseFloat()NumberFormatException如果String不是数字并且无法解析为 ,则将抛出a Float。您可以添加一个try-catch块来检查这种情况:

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
    float num1, num2, result;

    try {
        num1 = Float.parseFloat(jTextField1.getText());
        num2 = Float.parseFloat(jTextField2.getText());
        result = num1+num2;
        jTextField3.setText(String.valueOf(result));

    } catch (NumberFormatException e) {
        JOptionPane.showConfirmDialog(null, "Please enter numbers only", "naughty", JOptionPane.CANCEL_OPTION);
    }
}

回答by Borealid

try {
    Integer.parseInt(foo);
} catch (NumberFormatException e) {
    // Naughty
}

回答by polygenelubricants

If alphanumeric input is not valid for the Swing component in the first place, then instead of validating this post-entry, you should restrict the component to accept only certain format in the first place.

如果首先字母数字输入对 Swing 组件无效,那么您应该首先限制该组件仅接受特定格式,而不是验证此后输入。

Using the formatters that Swing provides, you can set up formatted text fields to type dates and numbers in localized formats. Another kind of formatter enables you to use a character mask to specify the set of characters that can be typed at each position in the field. For example, you can specify a mask for typing phone numbers in a particular format, such as (XX) X-XX-XX-XX-XX.

使用 Swing 提供的格式化程序,您可以设置格式化文本字段以本地化格式键入日期和数字。另一种格式化程序使您能够使用字符掩码来指定可以在字段中的每个位置键入的字符集。例如,您可以指定用于以特定格式键入电话号码的掩码,例如(XX) X-XX-XX-XX-XX.

That said, you can, among other things, use Integer.parseInt(String s)to see if an arbitrary string can be parsed into an int; the method throws NumberFormatExceptionif it can't. There are also Double.parseDouble, etc.

也就是说,除其他外,您可以使用Integer.parseInt(String s)来查看是否可以将任意字符串解析为int; NumberFormatException如果不能,该方法将抛出。还有Double.parseDouble,等等。

See also

也可以看看

Related questions

相关问题

回答by Jaymes Bearden

A relatively old question, but I figured I would take a shot at it, to maybe help out the random Google Searches.

一个相对古老的问题,但我想我会试一试,也许可以帮助随机谷歌搜索。

Another approach someone could take to minimise code and reduce the number of additional classes is to add a KeyListenerfor the keyType event and check for the Charvalue. This isn't very portable (you can't use region specific formatting such as numerical punctuation), but this could be quite helpful for straight integers. You could also do a relative length here as well:

有人可以采取的另一种方法来最小化代码并减少附加类的数量,即为KeyListenerkeyType 事件添加一个并检查Char值。这不是很便携(您不能使用特定于区域的格式,例如数字标点符号),但这对于直整数可能非常有用。你也可以在这里做一个相对长度:

textField.addKeyListener(new KeyAdapter()
{
    @Override
    public void keyTyped(KeyEvent keyEvent)
    {
        if (textField.getText().length() < 3 && keyEvent.getKeyChar() >= '0' && keyEvent.getKeyChar() <= '9')
        {
            // Optional
            super.keyTyped(keyEvent);
        }
        else
        {
            // Discard the event
            keyEvent.consume();
        }
    }
});

You can also add another event listener to validate the entire integer for further processing (the entire number must be > 800 and < 5220 for example). A good place for this would be on the focusLost event(?).

您还可以添加另一个事件侦听器来验证整个整数以供进一步处理(例如,整个数字必须 > 800 和 < 5220)。一个很好的地方是在 focusLost 事件(?)上。

If you are doing these features frequently, it would be best to subclass the JTextField class to provide this functionality.

如果您经常使用这些功能,最好将 JTextField 类子类化以提供此功能。

EDIT: Using Character.isLetter(keyEvent.getKeyChar())is even more clear.

编辑:使用Character.isLetter(keyEvent.getKeyChar())更清楚。

回答by Saurabh Jain

Try this:

尝试这个:

String temp = txtField.getText();
try 
  {
    int val = Integer.parseInt(temp);
  }
catch(NumberFormatException e) {
  System.out.println("Invalid");
 }

To make it more enjoyable, use JOptionPane (makes it more more interactive)

为了使它更有趣,请使用 JOptionPane(使其更具交互性)

回答by Nilkanth vithani

textFieldCrDays = new JTextField();
    textFieldCrDays.addKeyListener(new KeyAdapter() {
        //// validate onlu numeric value
        public void keyTyped(KeyEvent e) {
            if (textFieldCrDays.getText().length() < 3 && e.getKeyChar() >='0' && e.getKeyChar() <= '9')
            {
                // Optional
                super.keyTyped(e);
            }
            else
            {
                // Discard the event
                e.consume();
            }
        }
    });