What is the method for traversing and outputting a two-dimensional array in Java?
There are two commonly used methods for traversing and outputting a two-dimensional array in Java:
- Utilize nested loops: Use two nested loops for iterating through rows and columns respectively, and output each element.
int[][] array = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array[i].length; j++) {
System.out.print(array[i][j] + " ");
}
System.out.println();
}
The output result is:
1 2 3
4 5 6
7 8 9
- Use enhanced for loop: Use an enhanced for loop to iterate through each element in a two-dimensional array and output it.
int[][] array = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
for (int[] row : array) {
for (int num : row) {
System.out.print(num + " ");
}
System.out.println();
}
The output is:
1 2 3
4 5 6
7 8 9