(Java)如何使用 for-each 循环迭代双重 double[][] 2D 数组?

huangapple go评论76阅读模式
英文:

(java) How to iterate over double[][] 2d array using for each loop?

问题

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

extracted from my code.When I compile in terminal I receive "incompatible types: possible lossy conversion from double to int. I am trying to print out a double[][] as a matrix.

I am required to use afor each loop I know that the indexes have to be ints but how would I make sure they are when i can 't convert doubles to ints?

答案1

得分: 3

你可以像这样做:

// 首先迭代每一行
for (double[] rows : array) {
    // 然后对于该行,打印每个值。
    for (double v : rows) {
        System.out.print(v + "  ");
    }
    // 在每行后打印换行符
    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  
英文:

You can do it like this:

// 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();
}

For

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

Prints

1.0  2.0  3.0  
4.0  5.0  6.0  
7.0  8.0  9.0  


</details>



# 答案2
**得分**: 2

一个"for each"循环遍历值,而不是索引。此外,你只需要两个嵌套循环。

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

A for each loop loops over the values, not the indexes. Moreover, you only need two nested loops.

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

答案3

得分: 1

这是遍历二维数组的正确方式:

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

This is the right way to loop over 2d array

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

huangapple
  • 本文由 发表于 2020年10月21日 09:56:59
  • 转载请务必保留本文链接:https://go.coder-hub.com/64455607.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定