Source of StopLoopOnMismatch.java


  1: // StopLoopOnMismatch.java
  2: //  week06 code
  3: //  uses an InputMismatchException to end input of a summing loop

  5: import java.util.Scanner;
  6: import java.util.InputMismatchException;

  8: /**
  9:  * Uses an InputMismatchException to end input of a summing loop.
 10:  *
 11:  * @author Mark Young (A00000000)
 12:  */
 13: public class StopLoopOnMismatch {

 15:     public static void main(String[] args) {
 16:         Scanner kbd = new Scanner(System.in);
 17:         double num;
 18:         double sum = 0.0;

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

 31:         try {
 32:             System.out.print("Enter a number: ");
 33:             num = kbd.nextDouble();  kbd.nextLine();
 34:             while (num >= 0.0) {
 35:                 sum += num;
 36:                 System.out.print("Enter another number: ");
 37:                 num = kbd.nextDouble(); kbd.nextLine();
 38:             }
 39:         }
 40:         catch(InputMismatchException ime) {
 41:             System.out.println("\nThat's not a number!");
 42:             System.out.println("I'm going to assume you're done!");
 43:         }

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

 49:         System.out.print("\n\n");
 50:     }
 51: }