/**

*  This is example 2 of lab 3 in CS239 which provides practice in

*  exception handling. It prints the ratio  of each element in an

*  array divided by its successor and avoids computing a ratio

*  when the denominator would be 0.

*

*  @author  Dr. Bernstein

*  modified by Dr. Adams

*  date:  September 1, 2008

*/

   public class Example2_Key

   {

      public static void main(String[] args)

      {

         int        i, ratio;

         int[]      numbers = {100,10,0,5,2,8,0,30};

         i = 0;

               

               // note that we had to stop at length-1 or we would

               // have exceeded the bounds of the array

         for (i=0; i < numbers.length-1; i++)

         {

            try

            {       

                  // divide each array element by its successor

               ratio = numbers[i] / numbers[i+1];

               System.out.println(numbers[i]+"/"+numbers[i+1]+"="+ratio);

            }  // end try

 

                 // note the use of initials of exception class

                 // name as identifier

            catch (ArithmeticException ae)

            {

                  // catches exception that would occur when division by

                  // 0 would occur because number[i+1] is 0.  

               System.out.println("Couldn't calculate "+

               numbers[i]+"/"+numbers[i+1]);

            } // end catch

         }// end for

         System.out.println ("Done");

    } // end main

} // end class