public class BadDataSkipper2
2: import java.util.Scanner;
3: import java.util.InputMismatchException;
5: /**
6: * Another program that skips bad data entered by the user.
7: *
8: * @author Mark Young (A00000000)
9: */
10: public class BadDataSkipper2 {
12: public static void main(String[] args) {
13: Scanner kbd = new Scanner(System.in);
15: // introduce yourself
16: System.out.print("\n\n"
17: + "Catching IO Exceptions\n"
18: + "----------------------\n"
19: + "\n"
20: + "This program catches when the user types the wrong kind "
21: + "of value and tries to\ncarry on regardless.\n");
22: System.out.print("\n"
23: + "Enter numbers below and I will calculate their sum. "
24: + "Enter a negative number to\nend your list.\n\n");
26: // get started
27: double sum = 0.0;
28: System.out.print("Enter a number: ");
29: double num = kbd.nextDouble();
30: kbd.nextLine();
32: // keep going until get a negative number
33: while (num >= 0.0) {
34: sum += num;
35:
36: // keep going until get a number
37: while (true) {
38: try {
39: System.out.print("Enter another number: ");
40: num = kbd.nextDouble();
41: kbd.nextLine();
42: break; // from the while(true) loop
43: } catch (InputMismatchException ime) {
44: System.out.println("That's not a number!");
45: System.out.println("I'm going to skip it!");
46: kbd.nextLine();
47: }
48: }
49: }
51: // report result
52: System.out.println("The sum of the numbers you entered was " + sum);
53: System.out.print("\n\n");
54: }
55: }