My code is supposed to take float value inputs from a user and once the user inputs 2 invalid inputs in a row (non float) the program stops and sums up the valid inputs and spits out the sum to the user. Here is the code: System.out.println("Please input a set of float values.");
Scanner keyboard = new Scanner(System.in);
int tries = 0;
int maxTries = 2;
double sum = 0;
while (tries < 2) {
try {
while (keyboard.hasNext()){
sum += keyboard.nextDouble();
tries = 0; // reset counter because of valid input
}
}
catch (InputMismatchException e) {
System.out.println("Invalid input. Float values "
+ "only please.");
tries += 1; // tries +1 because invalid input
}
}
System.out.printf("The sum of your inputs is: %d", sum);
My exception is being thrown prematurely, once I put in one invalid input the program stops and sums up. I can't figure out how to allow the user two consecutive invalid (non float) inputs and then throw the exception. Thanks.