How to validate if Text entered is a numeric number?

倾然丶 夕夏残阳落幕 提交于 2019-12-07 20:58:43

问题


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.

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?


回答1:


Float.parseFloat() will throw a NumberFormatException if the String isn't numeric and cannot be parsed into a Float. You can add a try-catch block to check for this condition:

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



回答2:


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.

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.

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 NumberFormatException if it can't. There are also Double.parseDouble, etc.

See also

  • Java Tutorials/Swing/How to use Formatted Text Field
    • How to use the Focus Subsystem/Input Validation
  • Java Tutorials/Internationalization/Formatting - Numbers and Currencies

Related questions

  • A simple way to create a text field (or such) that only allows the user to enter ints/doubles in Java?
  • A textbox class only accept integers in Java
  • Validating an integer or String without try-catch - java.util.Scanner option



回答3:


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



回答4:


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)




回答5:


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();
            }
        }
    });



回答6:


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 KeyListener for the keyType event and check for the Char value. 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:

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(?).

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

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



来源:https://stackoverflow.com/questions/3412135/how-to-validate-if-text-entered-is-a-numeric-number

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