在Java中,遍历二维数组可以通过以下几种方法实现:
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();
}
3. 使用Java 8的流API:
int[][] array = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
Arrays.stream(array).forEach(row -> {
Arrays.stream(row).forEach(System.out::print);
System.out.println();
});
以上方法都可以用来遍历二维数组,并打印出数组的每个元素。选择哪种方法取决于你的具体需求和代码风格。