An alarm continues to cycle when an exception is caught

I am trying to continue asking the user for a valid payment if an invalid bid (including a letter) is provided. The problem is that if I enter a letter instead of a number, I will receive the message "Payrate must be > 0"endlessly; however, if I specify 0 or a negative number, I will be prompted as expected.

What am I doing wrong and how to fix it?

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;
    }
}
+4
source share
6 answers

The problem is that the class Scannerdoes not clear the input if an exception occurs, so it continues to feed itself with the letter if it is typed.

, payrate .

, :

String value;

while (true) { // Repeat until a valid payrate is entered
    try {
        System.out.print("Enter payrate: "); // Ask for payrate

        value = input.nextLine();            // Get payrate as string
        payrate = Float.parseFloat(value);   // Convert the string to float

        if (payrate > 0) { // Valid payrate number (> 0), done
            break;
        } else {           // Invalid payrate number (<= 0), repeat
            System.out.println("Payrate must be > 0.");
        }
    } catch (NumberFormatException e) { // Payrate not a number, repeat
        System.out.println("Payrate must be a number.");
    }
}
+2

input.next() , .nextFloat() .

+4

BufferReader .

BufferedReader bufferRead = new BufferedReader(new InputStreamReader(System.in));

Float s = Float.parseFloat(bufferRead.readLine());

, ...

+2

:

while (payrate <= 0) {
    try {
        System.out.print("Enter payrate: "); //ask for payrate
        payrate = Float.parseFLoat(input.next()); //Converts string to float
    } catch (NumberFormatException nfe) {  //I changed the exception catched
        System.out.println("Invalid number! Payrate must be > 0.");
        payrate = 0;
    }
}
+1

, nextFloat() float. InputMissmatchException, float, , float ,

Remember, when you declared a float variable and assigned any float value, you must write a "f" value. try with 10.10f

+1
source

In order to stay close to what has already been done, since the exception fell into the invalid content, we can clear the scanner from incorrect input. input.nextLine()will read invalid input. Doing nothing with the value caught ignores it.

Solution: Just add input.nextLine();catch to your block.

           try {
                System.out.print("Enter payrate: "); //ask for payratea
                payrate = input.nextFloat();  //store input from console
            } catch (Exception InputMismatchException) {
                System.out.println("Payrate must be > 0.");
                payrate = 0;
                input.nextLine();
            }
+1
source

All Articles