Java Reference
In-Depth Information
6
// create and output two-dimensional arrays
7
public static void main(String[] args)
8
{
9
int [][] array1 = {{ 1 , 2 , 3 }, { 4 , 5 , 6 }};
int [][] array2 = {{ 1 , 2 }, { 3 }, { 4 , 5 , 6 }};
10
11
12
System.out.println( "Values in array1 by row are" );
13
outputArray(array1); // displays array1 by row
14
15
System.out.printf( "%nValues in array2 by row are%n" );
16
outputArray(array2); // displays array2 by row
17
}
18
19
// output rows and columns of a two-dimensional array
20
public static void outputArray(
int [][] array
)
21
{
22
// loop through array's rows
for ( int row = 0 ; row < array.length; row++)
{
// loop through columns of current row
for ( int column = 0 ; column < array[row].length; column++)
System.out.printf( "%d " , array[row][column]);
System.out.println();
}
23
24
25
26
27
28
29
30
31
}
32
} // end class InitArray
Values in array1 by row are
1 2 3
4 5 6
Values in array2 by row are
1 2
3
4 5 6
Fig. 7.17 | Initializing two-dimensional arrays. (Part 2 of 2.)
Lines 13 and 16 call method outputArray (lines 20-31) to output the elements of
array1 and array2 , respectively. Method outputArray 's parameter— int[][] array —
indicates that the method receives a two-dimensional array. The nested for statement
(lines 23-30) outputs the rows of a two-dimensional array. In the loop-continuation con-
dition of the outer for statement, the expression array.length determines the number of
rows in the array. In the inner for statement, the expression array[row].length deter-
mines the number of columns in the current row of the array. The inner for statement's
condition enables the loop to determine the exact number of columns in each row. We
demonstrate nested enhanced for statements in Fig. 7.18.
Common Multidimensional-Array Manipulations Performed with for Statements
Many common array manipulations use for statements. As an example, the following for
statement sets all the elements in row 2 of array a in Fig. 7.16 to zero:
 
Search WWH ::




Custom Search