Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 576
Misoxeny Avatar asked Dec 09 '22 18:12

Misoxeny


1 Answers

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.");
    }
}
like image 189
tckmn Avatar answered Dec 11 '22 06:12

tckmn