12.7 Testing and Debugging | 619
12.7 Testing and Debugging
Errors with multidimensional arrays usually fall into two major categories: index ex-
pressions that are out of order and index range errors. We have been very careful to use
an array object’s own lengthvalue in loop expressions so as to minimize range errors.
However, inadvertent switching of indexes can cause index range errors.
Take a look at the code for dotProduct. What happens if we reverse the indexes in the
following statement?
total = total + matrix[row][index]*two.matrix[index][col];
That is, what happens if we code the statement as follows?
total = total + matrix[index][row]*two.matrix[col][index]; // Wrong
If the first matrix is a 35 and the second is a 52,indexgoes from 0 through 4 while
rowandcolremain at 0.matrix[ 0 ][ 0 ]andtwo.matrix[ 0 ][ 0 ]are accessed; thenmatrix[ 1 ][ 0 ]
andtwo.matrix[ 0 ][ 1 ]are accessed; thenmatrix[ 2 ][ 0 ]andtwo.matrix[ 0 ][ 2 ]are accessed.
This last access causes anArrayIndexOutOfBoundsExceptionto be thrown:two.matrix[ 0 ][ 2 ]
doesn’t exist.
How can you avoid such errors? This question has no simple answer. You just have to
be careful and thoroughly test your code.
Testing and Debugging Hints
1.With multidimensional arrays, use the proper number of indexes when refer-
encing an array component, and make sure the indexes are in the correct or-
der.
2.In loops that process multidimensional arrays, double-check the upper and
lower bounds on each index variable to verify that they are correct for that di-
mension of the array.
3.When declaring a multidimensional array as a parameter, confirm that you
have the proper number of brackets beside the type on the parameter list.
4.When passing an array object as an argument, be sure that it has the same
number of dimensions as the parameter of the method to which it is being
passed.