Java Reference
In-Depth Information
SR 8.22 Write a method called travelTime that accepts an integer parameter
indicating average speed followed by a multiple number of integer
parameters (each of which represents the distance of one leg of a jour-
ney) and returns the total time of the trip.
8.6 Two-Dimensional Arrays
The arrays we've examined so far have all been one-dimensional arrays in the
sense that they represent a simple list of values. As the name implies, a two-
dimensional array has values in two dimensions, which are often thought of as the
rows and columns of a table. Figure 8.4 graphically compares a one-dimensional
array with a two-dimensional array. We must use two indexes to refer to a value
in a two-dimensional array, one specifying the row and another the column.
Brackets are used to represent each dimension in the array. Therefore the type
of a two-dimensional array that stores integers is int [][] . Technically, Java rep-
resents two-dimensional arrays as an array of arrays. A two-dimensional integer
array is really a one-dimensional array of references to one-dimensional integer
arrays.
The TwoDArray program shown in Listing 8.13 instantiates a two-
dimensional array of integers. As with one-dimensional arrays, the size of the
dimensions is specified when the array is created. The size of the dimensions
can be different.
Nested for loops are used in the TwoDArray program to load the array with val-
ues and also to print those values in a table format. Carefully trace the processing
to see how the nested loops eventually visit each element in the two-dimensional
array. Note that the outer loops are governed by table.length , which represents
the number of rows, and the inner loops are governed by table[row].length ,
which represents the number of columns in that row.
one dimension
two dimensions
FIGURE 8.4 A one-dimensional array and a two-dimensional array
 
Search WWH ::




Custom Search