Source of CatchSumException.java


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

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

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

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

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

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

 39: }