(java)如何使用for each循环在double[][]2d数组上迭代


for (double[] row: array) {
for (double x: row) {
for (double[] col: array) {
for (double y: col) {
System.out.println(array[x][y]);
}
}
}
}

从我的代码中提取。当我在终端中编译时;不兼容类型:从double到int的可能有损转换。我正试图将double[][]打印为矩阵。

我需要在每个循环中使用af我知道索引必须是int,但当我不能将double转换为int时,我该如何确保它们是int?

你可以这样做:

// first iterate each row
for (double[] rows : array) {
// then for that row, print each value.
for (double v : rows) {
System.out.print(v + "  ");
}
// print new line after each row
System.out.println();
}

对于

double[][] a = new double[][] { { 1,2,3 }, {4,5,6 }, { 7,8,9 } };

打印

1.0  2.0  3.0  
4.0  5.0  6.0  
7.0  8.0  9.0  

每个循环的一个循环都在值上循环,而不是在索引上循环。此外,您只需要两个嵌套循环。

final double[][] array = {{1, 2}, {3, 4}, {5, 6}};
for (double[] row: array) {
for (double element: row) {
System.out.println(element);
}
}

这是在2d阵列上循环的正确方法

for (double [] row : array) {
for (double value : row) {
System.out.println(value);
}
}

最新更新