Source of BadDataSkipper1.java


  2: import java.util.Scanner;
  3: import java.util.InputMismatchException;

  5: /**
  6:  * A program that skips bad data entered by the user.
  7:  *
  8:  * @author Mark Young (A00000000)
  9:  */
 10: public class BadDataSkipper1 {

 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 #
 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 skip it!");
 42:                 kbd.nextLine();
 43:                 num = 0.0;  // so sum doesn't get messed up!
 44:             }
 45:         }

 47:         // report result
 48:         System.out.println("The sum of the numbers you entered was " + sum);
 49:         System.out.print("\n\n");
 50:     }
 51: }