Having trouble with some basic code here. We have an array class that lets the array start at variable indexes. I've encountered problems with throwing exceptions. With the add method, the exception for adding to an occupied cell works correctly but I can not get my custom message for out of bounds to show up. I get the generic arrayoutofbounds exception.
class Array<T extends Comparable<? super T>> { // Data fields private T[] array; private int firstIndex, lastIndex, arraySize; // Constructor public Array(int first, int last) { firstIndex = first; lastIndex = last; arraySize = last - first + 1; array = (T[]) new Comparable[arraySize]; } // If the index i is out of range, throw an exception with an appropriate // message. // If there is already an object at the index, throw an exception. // Otherwise, add the object x into array at index i. public void add(T x, int i) throws Exception { if (array[i - firstIndex] == null) { if (i >= firstIndex && i <= lastIndex) { array[i - firstIndex] = x; } else { throw new Exception("wsefwef"); } } else throw new Exception(i + " is not vacant"); } // Print array public void print() { String string = ""; String label = ""; for (int i = 0; i < arraySize; i++) { string += "[ " + array[i] + " ]"; } System.out.println(string); System.out.println(label); } }
class Prog1 { public static void main(String[] args) { Array<Integer> array = new Array<Integer>(3, 7); // Array indices are 3, 4, 5, 6, and 7 // Testing of methods from Array using array System.out.println("Array at the Start"); array.print(); System.out.println(); //Add method System.out.println("Test add Method"); System.out.println( "Put value 3 in 5 index"); try { array.add(3,5); System.out.println("Success"); } catch (Exception e) { System.out.println(e); } array.print(); System.out.println( "Put value 3 in 5 index again( already full"); try { array.add(3,5); System.out.println("Success"); } catch (Exception e) { System.out.println(e); } array.print(); System.out.println( "Put value 3 in 10 index( Out of Bounds "); try { array.add(3,10); System.out.println("Success"); } catch (Exception e1) { System.out.println(e1.getMessage()); } array.print(); } }