I'm trying to figure out why my program is skipping a user input so I can come up with a solution. If I intentionally give it bad input and cause the InputMismatchException to be thrown, it skips the inputDouble = in.nextDouble();
line. Here is what the output looks like:
Please enter floating point value or -1 to stop
15.7
Please enter floating point value or -1 to stop
15.7
Please enter floating point value or -1 to stop
r
Number format is incorrect please try again
Please enter floating point value or -1 to stop
Number format is incorrect please try again
Total is: 31.4
And here is my code
import java.util.InputMismatchException;
import java.util.Scanner;
public class AddingNumbers {
public static void main(final String[] args) {
Scanner in = new Scanner(System.in);
double inputDouble = 0;
double total = 0;
int tries = 0;
boolean done = false;
while (!done) {
if (tries < 2) {
try {
System.out.println("Please enter floating point value or -1 to stop");
inputDouble = in.nextDouble();
if (inputDouble != -1) {
total = total + inputDouble;
} else {
System.out.println("Total is: " + total);
done = true;
}
} catch (InputMismatchException exception) {
System.out.println("Number format is incorrect please try again");
tries++;
}
} else {
System.out.println("Total is: " + total);
done = true;
}
}
in.close();
}
}