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

1.1k Views Asked by At
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?

3

There are 3 best solutions below

0
On BEST ANSWER

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  
0
On

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);
    }
}
2
On

This is the right way to loop over 2d array

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