Source of ArrayFails.java


  1: import java.util.Scanner;

  3: /**
  4:  * Exceptions thrown by arrays and array elements.
  5:  *
  6:  * @author Mark Young (A00000000)
  7:  */
  8: public class ArrayFails {

 10:     private static final Scanner KBD = new Scanner(System.in);

 12:     public static void main(String[] args) {
 13:         // for the test number
 14:         int testNumber;

 16:         // create two array VARIABLES
 17:         String[] notCreated;
 18:         String[] notFilled;

 20:         // BUT create only ONE array OBJECT
 21:         notCreated = null;
 22:         notFilled = new String[10];

 24:         // choose a test based on the command line argument OR input
 25:         if (args.length > 0) {
 26:             // args[0] should be a test number
 27:             testNumber = Integer.parseInt(args[0]);
 28:         } else {
 29:             // need to ask user for test number
 30:             System.out.print("\nWhich test do you want, 1, 2, or 3? ");
 31:             testNumber = KBD.nextInt();
 32:             KBD.nextLine();
 33:         }

 35:         // carry out the chosen test
 36:         System.out.println("\nTest #" + testNumber + ":");
 37:         if (testNumber == 1) {
 38:             // NullPointerException becaue of not-created array
 39:             System.out.println("Trying to print notCreated[5]");
 40:             System.out.println(notCreated[5]);
 41:         } else if (testNumber == 2) {
 42:             // ArrayIndexOutOfBoundsException because array only has 10 elements
 43:             System.out.println("Trying to print notFilled[15]");
 44:             System.out.println(notFilled[15]);
 45:         } else if (testNumber == 3) {
 46:             // NullPointerException because array element is null
 47:             System.out.println("Trying to print notFilled[5].length()");
 48:             System.out.println(notFilled[5].length());
 49:         } else {
 50:             System.out.println("Sorry, but " + testNumber 
 51:                     + " is not one of the three tests we have.");
 52:         }
 53:     }

 55: }