public class CatchInputMismatch
2: import java.util.Scanner;
3: import java.util.InputMismatchException;
5: /**
6: * A program that catches bad data entered by the user.
7: *
8: * @author Mark Young (A00000000)
9: */
10: public class CatchInputMismatch {
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 you get a negative #
33: while (num >= 0.0) {
34: try {
35: sum += num;
36: System.out.print("Enter another number: ");
37: num = kbd.nextDouble();
38: kbd.nextLine();
39: } catch (InputMismatchException ime) {
40: System.out.println("That's not a number!");
41: System.out.println("I'm going to assume you're done!");
42: break;
43: }
44: }
46: // report results
47: System.out.println("The sum of the numbers you entered was " + sum);
48: System.out.print("\n\n");
49: }
50: }