简体   繁体   中英

In Java, how do I check if input is a number?

I am making a simple program that lets you add the results of a race, and how many seconds they used to finish. So to enter the time, I did this:

int time = Integer.parseInt(JOptionPane.showInputDialog("Enter seconds"));

So my question is, how can I display an error message to the user if he enters something other than a positive number? Like a MessageDialog that will give you the error until you enter a number.

int time;
try {
    time = Integer.parseInt(JOptionPane.showInputDialog("Enter seconds"));
} catch (NumberFormatException e) {
    //error
}

Integer.parseInt will throw a NumberFormatException if it can't parse the int . If you just want to retry if the input is invalid, wrap it in a while loop like this:

boolean valid = false;
while (!valid) {
    int time;
    try {
        time = Integer.parseInt(JOptionPane.showInputDialog("Enter seconds"));
        if (time >= 0) valid = true;
    } catch (NumberFormatException e) {
        //error
        JOptionPane.showConfirmDialog("Error, not a number. Please try again.");
    }
}

Integer.parseInt Throws NumberFormatException when the parameter to Integer.parseInt is not a integer, Use try Catch and display required error message, keep it in do while loop as below

   int   time = -1;
   do{
       try{
            time = Integer.parseInt(JOptionPane.showInputDialog("Enter seconds"));
       }
       catch(NumberFormatException e){

       }
   }while(time<=0);

如果JOptionPane.showInputDialog("Enter seconds")不是有效数字,您将获得NumberFormatException 。对于正数检查,只需检查time >=0

Depends on how you want to solve it. An easy way is to declare time as an Integer and just do:

Integer time;    
while (time == null || time < 0) {
    Ints.tryParse(JOptionPane.showInputDialog("Enter seconds"));
}

Of course that would require you to use google guava. (which contains a lot of other useful functions).

Another way is to use the above code but use the standard tryparse, catch the NumberFormatException and do nothing in the catch.

There are plenty of ways to solve this issue.

Or not reinvent the wheel and just use: NumberUtils.isNumber or StringUtils.isNumeric from Apache Commons Lang .

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