Search code examples
javaforeach-loop-container

(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[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?


Solution

  • 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