Source of CatchSumException.java


  1: package exceptions;

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

  6: /**
  7:  * A class to sum up numbers provided by the user.
  8:  *
  9:  * @author Mark Young (A00000000)
 10:  */
 11: public class CatchSumException {

 13:     public static final Scanner KBD = new Scanner(System.in);

 15:     public static void main(String[] args) {
 16:         int num, sum;

 18:         // introduce yourself
 19:         System.out.println("Enter some positive integers below "
 20:                 + "and I'll tell you their sum.");

 22:         // add up the user input
 23:         try {
 24:             sum = 0;
 25:             num = KBD.nextInt();
 26:             while (num >= 0) {
 27:                 sum += num;
 28:                 System.out.println("The sum is now " + sum + ".");
 29:                 num = KBD.nextInt();
 30:             }
 31:         
 32:             // report result
 33:             System.out.println("Their sum is " + sum + ".");
 34:         } catch (InputMismatchException ime) {
 35:             System.out.println(KBD.next() + " is not an integer.");
 36:             System.out.println("Your program would have crashed "
 37:                     + "if I hadn't caught that exception!");
 38:         }
 39:     }

 41: }