Homework 10
1.
SafeIntArrayclass (5 points)A student had a good idea and defined a new
SafeIntArrayclass that would throw a descriptiveArrayIndexOutOfBoundsExceptionwhenever someone tried to read from a location that did not exist in the array. This new class gives some more information in the error messages generated by thegetElementAtmethod. However, they forgot to apply the idea to thesetElementAtmethod, which allows someone to write a value to particular location in the array.
- Modify the
setElementAtmethod in theSafeIntArrayclass so that it will throw anArrayIndexOutOfBoundsExceptionwhen a specifiedindexis less than 0 or greater than the last possible index in the array. (HINT: refer to thegetElementAtmethod as a guide)2.
SafeIntArrayTestclass (10 points)The student also defined a test class
SafeIntArrayTestto test the functionality of their newSafeIntArrayclass. Unfortunately, their test program crashes whenever an out of bounds index is entered by the user. Fix this problem in two ways (you should have two separate modifiedSafeIntArrayTestprograms when you are done):
- Insert some
tryandcatchstatements to keep the program from crashing. If the user enters an index that is out of bounds, your modified program shouldcatchthe resulting exception, tell the user they went out of bounds, and allow them to continue entering values. A possible output might look something like the following:Please enter an index to read (-1 to quit): 12 the element at index 12 is 35 Please enter another index (-1 to quit): 34 index 34 exceeds the maximum index [19] Please enter another index (-1 to quit): -2 index -2 precedes the minimum index [0]- Instead of using the
tryandcatchstatements, just test to make sure that the index [entered by the user] is not out of bounds before you call thegetElementAtmethod. The user should again be able to continue entering values after a bad index (just like above). The only difference is you are checking for a bad value before you try and retrieve it, instead of just trying to retrieve the value at the specified index and catching the execption, as in the previous problem.