Misoxeny Misoxeny - 1 month ago 6
Java Question

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.

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