Source of Thing.java


  1: package arrayexceptions;

  3: /**
  4:  * A class with an array inside to help demonstrate how to fix exceptions with
  5:  * arrays.  The array saves a limited number of the powers of 2 as int values.
  6:  * 
  7:  * @author Mark Young (A00000000)
  8:  */
  9: public class Thing {
 10:     public static final int DEFAULT_SIZE = 10;
 11:     private int[] numbers;
 12:     
 13:     /**
 14:      * Create an array saving the first <code>howBig</code> powers of two.
 15:      * 
 16:      * @param howBig how many powers of two to save.
 17:      */
 18:     public Thing(int howBig) {
 19:         if (howBig >= 0) {
 20:             numbers = new int[howBig];
 21:         } else {
 22:             // numbers = new int[DEFAULT_SIZE];
 23:             System.out.println("Illegal size: " + howBig);
 24:             System.out.println("Using default size");
 25:         }
 26:         fill(numbers);
 27:     }
 28:     
 29:     /**
 30:      * Save a default number of the powers of two.
 31:      */
 32:     public Thing() {
 33:         this(DEFAULT_SIZE);
 34:     }
 35:     
 36:     /**
 37:      * Return the value of 2^n from the stored list of values.
 38:      * @param n the power of 2 requested
 39:      * @return the value of 2^n, if it's in the list
 40:      * @throws ArrayIndexOutOfBoundsException if n is not in the list
 41:      */
 42:     public int powerOfTwo(int n) {
 43:         return numbers[n];
 44:     }
 45:     
 46:     /**
 47:      * Fills an array with powers of two.
 48:      * 
 49:      * @param arr the array to fill
 50:      */
 51:     private static void fill(int[] arr) {
 52:         for (int i = 0; i < arr.length; ++i) {
 53:             arr[i] = (int)Math.pow(2, i);
 54:         }
 55:     }
 56: }