So here's the problem
Write a program that asks the user to input a set of floating-point values. When the user enters a value that is not a number, give the user a second chance to enter the value. After two chances, quit reading input. Add all correctly specified values and print the sum when the user is done entering data. Use a sentinel value to signal the end of input. Use exception handling to detect improper inputs. Here is a sample program run:
Value: 1
Value: 2
Value: three
Input error. Try again.
Value: 3
Value: four
Input error. Try again.
Value: 4
Value: five
Input error. Try again.
Value: cinq
Input error. Try again.
Sum: 10.0
Here's what I'm trying to do.
while (flagA)
{
try {
while (flagB)
{
try {
System.out.print("Value: ");
num = input.nextFloat();
sum += num;
}
catch (InputMismatchException e) {
System.out.println("Input error. Try again.");
flagB = false;
}
}
System.out.print("Value: ");
num = input.nextFloat();
sum += num;
flagB = true;
}
catch (InputMismatchException f) {
System.out.println("Input error. Try again");
flagA = false;
}
}
System.out.println(sum);
Basically, I execute my inner loop first to read a floating-point value from the user-input. Then, if an invalid entry is detected, an exception is thrown, leading to the outer try block. This try block also checks for valid user input. If the user enters a wrong number the second time, the loop breaks and the sum of all valid inputs is printed. Otherwise, it will continue to take a valid input until 2 consecutive invalid entries are read.
Am I supposed to use nested try blocks like this?
I think my solution is really close but I can't seem to bridge the gap here.