Programming and Problem Solving with Java

(やまだぃちぅ) #1

(^510) | One-Dimensional Arrays


10.8 Testing and Debugging


The most common error in processing arrays is an out-of-bounds array index. That is, the
application attempts to access a component by using an index that is either less than zero
or greater than the array size minus one. For example, given the declarations

String[] line = newString[ 100 ];
int counter;

the following forstatement would print the 100 elements of the linearray and then try
to print a one hundred first value—the value that resides in memory immediately be-
yond the end of the array:

for(counter = 0 ; counter <= line.length; counter++)
outfile.println(line[counter]);

This error is easy to detect, because your application will halt with an
ArrayIndexOutOfBoundsException. The loop test should becounter <line.length. You won’t al-
ways use a simpleforstatement when accessing arrays, however. Suppose we read data into
thelinearray in another part of the application. Let’s use awhilestatement that reads to the
end of the file:

counter = 0 ;
inString = infile.readLine();
while(inString != null)
{
line[counter] = inString;
counter++;
inString = infile.readLine();
}

This code seems reasonable enough, but what if the input file has more than 100 lines?
After the one-hundredth line is read and stored into the array, the loop executes one more
time and the ArrayIndexOutOfBoundsExceptionis thrown, causing the application to crash.
The moral is this: When processing arrays, pay special attention to the design of loop
termination conditions. Always ask yourself if the loop could possibly keep running after
the last array component has been processed.
Whenever an array index goes out of bounds, your first suspicion should be a loop that
fails to terminate properly. The second thing to check for is array access involving an in-
dex that is based on an input value or a calculation. When an array index is input as data,
a data validation check is an absolute necessity.
As we have demonstrated in many examples in the last several chapters, it is possible
to combine data structures in various ways: classes whose components are objects, classes

T


E


A


M


F


L


Y


Team-Fly®

Free download pdf