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

冷暖自知 提交于 2019-12-01 05:02:35

问题


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.


回答1:


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



回答2:


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



回答3:


If JOptionPane.showInputDialog("Enter seconds") is not a valid number, you will be getting NumberFormatException.For positive number check, just check time >=0




回答4:


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.



来源:https://stackoverflow.com/questions/14359930/in-java-how-do-i-check-if-input-is-a-number

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