简体   繁体   中英

Having trouble understanding this example on Multidimensional Array

For the code:

// Demonstrate a two-dimensional array.
class TwoDArray {
    public static void main(String args[]) {
        int twoD[][] = new int[4][5];
        int i, j, k = 0;
        for (i = 0; i < 4; i++)
            for (j = 0; j < 5; j++) {
                twoD[i][j] = k;
                k++;
            }
        for (i = 0; i < 4; i++) {
            for (j = 0; j < 5; j++)
                System.out.print(twoD[i][j] + " ");
                System.out.println();
        }
    }    
}

The output gives me:

0 1 2 3 4

5 6 7 8 9

10 11 12 13 14

15 16 17 18 19

The question is, why isn't new line given to every numbers? I mean in the for Loop, if the first System.out outputted 20 times, why isn't the next System.out.println(); outputting the same amount?

If you used proper indentation, it would have been clearer :

for (i=0; i<4; i++) {
    for (j=0; j<5; j++)
        System.out.print(twoD[i][j] + " ");
    System.out.println();
}

System.out.println(); belongs to the outer loop, so it executes once for every iteration of the outer loop, after the inner loop ends.

You can also wrap the inner loop in curly braces to make it clearer :

for (i=0; i<4; i++) {
    for (j=0; j<5; j++) {
        System.out.print(twoD[i][j] + " ");
    }
    System.out.println();
}

Without braces, a for loop body is one statement. If we add explicit braces, then your code looks like

for(i=0; i<4; i++) {
    for(j=0; j<5; j++) {
        System.out.print(twoD[i][j] + " ");
    }
    System.out.println();
}

which is why the println only executes after the inner for loop.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM