简体   繁体   中英

How do i make a check for in the input is a number or not in swing?

So i was making an application where the user enters an input, and when he clicks the button it executes a command, however the input has to be an integer, so i added a check but even when i enter an integer is gives me an error saying "you can enter numbers only!"

heres my code :

        String itemId = textField1.getText();
        String itemAmount = textField2.getText();

        int id = Integer.parseInt(itemId);
        int amount = Integer.parseInt(itemAmount);

        if (!Double.isNaN(id) || !Double.isNaN(amount)){
            JOptionPane.showMessageDialog(
                    null, "You can only enter numbers!"
            );

even after i enter numbers to the textFields i still cannot pass this test, why and how can i fix this ? thanks.

however the input has to be an integer, so i added a check but even when i enter an integer is gives me an error saying "you can enter numbers only!"

there are two ways, to use

  • JFormattedTextField with number formatter, JSpinner with SpinnerNumberModel

  • add DocumentFilter to JTextField

Actually you can just do it like this:

String itemId = textField1.getText();
String itemAmount = textField2.getText();
int id;
int amount;
try{
    id = Integer.parseInt(itemId);
    amount = Integer.parseInt(itemAmount);
}
catch(NumberFormatException e){
        JOptionPane.showMessageDialog(null, "You can only enter numbers!");
}

If itemID and itemAmount value is not parse-able, means non-digit was entered

 Double.isNaN(id)

Returns true if the specified number is a Not-a-Number (NaN) value, false otherwise.

But your id and your amout are Integers so it will return false and you do !Double.isNaN(id) and invert the boolean, so the result is true. Its only an logical failure. Remove the ! .

if (Double.isNaN(id) || Double.isNaN(amount)){
    JOptionPane.showMessageDialog(null, "You can only enter numbers!");
}

Note:

int id = Integer.parseInt(itemId);
int amount = Integer.parseInt(itemAmount);

Sourround this two lines with an try and catch block, otherwise you will get an NumberFormatException if the input is not numeric.

try
{
    int id = Integer.parseInt(itemId);
    int amount = Integer.parseInt(itemAmount);+
}catch(NumberFormatException e)
{
    //print your error here
}

如果您不想使用JFormattedTextField,请使用Apache的StringUtils.isNumeric()方法。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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