Source of ArrayExceptions.java


  1: package arrayexceptions;

  3: import java.util.Arrays;

  5: /**
  6:  * Just a program to show some exceptions you might run into.  See the course
  7:  * notes for instructions on how to fix them.
  8:  * 
  9:  * @author Mark Young (A00000000)
 10:  */
 11: public class ArrayExceptions {

 13:     /**
 14:      * @param args the command line arguments
 15:      */
 16:     public static void main(String[] args) {
 17:         // ArrayIndexOutOfBoundsException
 18:         int[] a = makeArray();
 19:         System.out.println(Arrays.toString(a));
 20:         
 21:         // NullPointerException (1) -- requires AIOOBE to be fixed
 22:         Thing t1 = new Thing(-1);
 23:         int n1 = t1.powerOfTwo(1);
 24:         System.out.println("2^1 == " + n1);
 25:         
 26:         // NullPointerException (2) -- requires NPE(1) to be fixed
 27:         Thing[] things = new Thing[100];
 28:         things[0] = t1;
 29:         System.out.println("2^5 == " + things[1].powerOfTwo(5));
 30:     }
 31:     
 32:     /**
 33:      * Create a five-element array containing the numbers 1 to 5.  
 34:      * NOTE: buggy!
 35:      * 
 36:      * @return a new array containing the numbers 1 to 5 in order.
 37:      */
 38:     private static int[] makeArray() {
 39:         int[] result = new int[5];
 40:         for (int i = 0; i <= 5; ++i) {
 41:             result[i] = i;
 42:         }
 43:         return result;
 44:     }

 46: }