Source of CatchInputMismatch.java


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

  5: /**
  6:  * Uses an InputMismatchException to end input of a summing loop.
  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);
 14:         double num;
 15:         double sum = 0.0;

 17:         System.out.print("\n\n"
 18:            + "Catching Input Mismatch Exceptions\n"
 19:            + "----------------------------------\n"
 20:            + "\n"
 21:            + "This program catches when the user types the wrong kind "
 22:            + "of value and tries to\ncarry on regardless.\n");
 23:         System.out.print("\n"
 24:            + "Enter numbers below and I will calculate their sum. "
 25:            + "Enter a negative number to\nend your list.\n\n");

 27:         try {
 28:             System.out.print("Enter a number: ");
 29:             num = kbd.nextDouble();  kbd.nextLine();
 30:             while (num >= 0.0) {
 31:                 sum += num;
 32:                 try {
 33:                     System.out.print("Enter another number: ");
 34:                     num = kbd.nextDouble(); kbd.nextLine();
 35:                 } catch(InputMismatchException ime) {
 36:                     System.out.println("\nThat's not a number!");
 37:                     System.out.println("I'm going to ignore it!\n");
 38:                     kbd.nextLine(); // to read and ignore whatever that was
 39:                     num = 0.0;      // so the sum doesn't get messed up!
 40:                 }
 41:             }

 43:             System.out.println("\n"
 44:                     + "The sum of the positive numbers you entered was " 
 45:                     + sum + ".");

 47:         } catch (InputMismatchException ime) {
 48:             System.out.println("\nNot even ONE number!");
 49:             System.out.println("There's no sum to print.");
 50:         }
 51:         System.out.print("\n\n");
 52:     }
 53: }