Hi,
I am having trouble getting back into a loop after an exception has been caught. This is what the program should do...
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 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
Your main class should be called DataReader.
Here is what I have so far...
import java.util.InputMismatchException;
import java.util.Scanner;
public class DataReader {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
float sum = 0;
float num = 0;
int count = 0;
boolean more = true;
System.out.println("Please enter a number...");
while (more) {
try {
num = scan.nextFloat();
System.out.println("Value: " + num);
sum = sum + num;
}
catch (InputMismatchException exception) {
System.out.println("Input Error. Try again.");
count++;
if (count >= 2) {
more = false;
}
num = scan.nextFloat();
}
}
System.out.println("Sum: " + sum);
}
}
After the exception has been caught, the user is given a second try to enter a good value before the program ends. That is where things are going wrong. How do I collect a value from the user after the exception has been caught?