Java Reference
In-Depth Information
7.2
Can the rows in a two-dimensional array have different lengths?
7.3
What is the output of the following code?
int
[][] array =
new int
[
5
][
6
];
int
[] x = {
1
,
2
};
array[
0
] = x;
System.out.println(
"array[0][1] is "
+ array[
0
][
1
]);
7.4
Which of the following statements are valid?
int
[][] r =
new int
[
2
];
int
[] x =
new int
[];
int
[][] y =
new int
[
3
][];
int
[][] z = {{
1
,
2
}};
int
[][] m = {{
1
,
2
}, {
2
,
3
}};
int
[][] n = {{
1
,
2
}, {
2
,
3
}, };
Nested
for
loops are often used to process a two-dimensional array.
Key
Point
Suppose an array
matrix
is created as follows:
int
[][] matrix =
new int
[
10
][
10
];
The following are some examples of processing two-dimensional arrays.
1.
Initializing arrays with input values.
The following loop initializes the array with user
input values:
java.util.Scanner input =
new
Scanner(System.in);
System.out.println(
"Enter "
+ matrix.length +
" rows and "
+
matrix[
0
].length +
" columns: "
);
for
(
int
row =
0
; row <
matrix.length
; row++) {
for
(
int
column =
0
; column <
matrix[row].length
; column++) {
matrix[row][column] = input.nextInt();
}
}
2.
Initializing arrays with random values.
The following loop initializes the array with
random values between
0
and
99
:
for
(
int
row =
0
; row < ; row++) {
for
(
int
column =
0
; column < ; column++) {
matrix[row][column] = (
int
)(Math.random() *
100
);
matrix.length
matrix[row].length
}
}
3.
Printing arrays.
To print a two-dimensional array, you have to print each element in the
array using a loop like the following:
for
(
int
row =
0
; row <
matrix.length
; row++) {
for
(
int
column =
0
; column <
matrix[row].length
; column++) {
System.out.print(matrix[row][column] +
" "
);
}
System.out.println();
}