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;
}
}
You could use input.next() in your exception, since .nextFloat() is not clearing the invalid value.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With