Homework 10
1.
SafeIntArray
class (5 points)A student had a good idea and defined a new
SafeIntArray
class that would throw a descriptiveArrayIndexOutOfBoundsException
whenever 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 thegetElementAt
method. However, they forgot to apply the idea to thesetElementAt
method, which allows someone to write a value to particular location in the array.
- Modify the
setElementAt
method in theSafeIntArray
class so that it will throw anArrayIndexOutOfBoundsException
when a specifiedindex
is less than 0 or greater than the last possible index in the array. (HINT: refer to thegetElementAt
method as a guide)2.
SafeIntArrayTest
class (10 points)The student also defined a test class
SafeIntArrayTest
to test the functionality of their newSafeIntArray
class. 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 modifiedSafeIntArrayTest
programs when you are done):
- Insert some
try
andcatch
statements to keep the program from crashing. If the user enters an index that is out of bounds, your modified program shouldcatch
the 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
try
andcatch
statements, just test to make sure that the index [entered by the user] is not out of bounds before you call thegetElementAt
method. 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.