1. 使用嵌套for循环:
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();
}
2. 使用增强for循环(foreach):
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();
}
这两种方法都可以遍历二维数组的外层,并输出每一行的元素。增强for循环使得代码更简洁,但嵌套for循环在需要更多控制时更加灵活