1

对于代码:

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

输出给了我:

0 1 2 3 4

5 6 7 8 9

10 11 12 13 14

15 16 17 18 19

问题是,为什么不给每个数字换行?我的意思是在 for 循环中,如果第一个 System.out 输出了 20 次,为什么下一个System.out.println();输出的量不一样?

4

2 回答 2

5

如果您使用适当的缩进,它会更清楚:

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

System.out.println();属于外循环,所以每次外循环迭代执行一次,在内循环结束后。

您还可以将内循环包裹在花括号中以使其更清晰:

for (i=0; i<4; i++) {
    for (j=0; j<5; j++) {
        System.out.print(twoD[i][j] + " ");
    }
    System.out.println();
}
于 2017-04-14T09:54:30.123 回答
2

没有大括号,for循环体就是一个语句。如果我们添加显式大括号,那么您的代码看起来像

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

这就是为什么println唯一在内for循​​环之后执行。

于 2017-04-14T09:54:51.223 回答