Try...Catch

C:\ece538>java StudentPoll2
java.lang.ArrayIndexOutOfBoundsException: Index 14 out of bounds for length 6  

Rating Frequency
     1         3
     2         4
     3         8
     4         2
     5         2


StudentPoll2.java

// Fig. 7.8: StudentPoll.java
// Poll analysis program, using alternative for loop

public class StudentPoll2 
{
   public static void main(String[] args)
   {
      // student response array (more typically, input at run time)
      int[] responses = {1, 2, 5, 14, 3, 5, 2, 1, 3, 3, 1, 4, 3, 3, 3, 
         2, 3, 3, 2, 4};
      int[] frequency = new int[6]; // array of frequency counters

      // for each answer, select responses element and use that value 
      // as frequency index to determine element to increment
      for (int answer: responses)
      {
         try
         {
            ++frequency[answer];
         } 
         catch (ArrayIndexOutOfBoundsException e)
         {
            System.out.println(e); // invokes toString method
          } 
      } 

      System.out.printf("%n%s%10s%n", "Rating", "Frequency");
   
      // output each array element's value
      for (int rating = 1; rating < frequency.length; rating++)
         System.out.printf("%6d%10d%n", rating, frequency[rating]);
   } 
}


Maintained by John Loomis, updated Sat Jan 18 17:06:06 2020