Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trouble continuing loop when exception caught

I'm trying to continue prompting the user for a valid payrate if an invalid rate (meaning including a letter) is supplied. The problem is that if I enter a letter instead of a number then I get the "Payrate must be > 0" message endlessly; however, if I enter 0 or a negative number I'm prompted as expected.

What am I doing wrong and how would I fix this?

while (payrate <= 0) {
    try {
        System.out.print("Enter payrate: "); //ask for payrate
        payrate = input.nextFloat();  //store input from console
    } catch (Exception InputMismatchException) {
        System.out.println("Payrate must be > 0.");
        payrate = 0;
    }
}
like image 453
jr0207 Avatar asked Dec 19 '22 19:12

jr0207


1 Answers

You could use input.next() in your exception, since .nextFloat() is not clearing the invalid value.

like image 86
Patrick J Abare II Avatar answered Jan 07 '23 07:01

Patrick J Abare II