难以理解多维数组上的这个例子

时间:2017-04-14 09:52:14

标签: java arrays for-loop multidimensional-array elementary

代码:

// 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();输出相同的数量呢?

2 个答案:

答案 0 :(得分: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();
}

答案 1 :(得分:2)

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

But the function throws back error ;
Error: invalid selector: No selector specified

Wanted to know how we can pass arguments stored in variables into various functions.

For instance in the code below , we are retiring sectionId via execute , storing it in sectionId variable .
then using it later on in moveToObject.

all functions seems to work when we are giving arguments inside "" quotes, but in our case we cannot do this. Please help us out how we can achieve this.

it('drag and drop should work', function() {
            var sectionId = "";
            // load page, then call function()
            return driver
                .url('http://localhost:9000')
                .pause(7000)
                .click('#layoutWizardButton')
                .click('#tableWizardBuild')
                .pause(3000)
                .execute(function() {
                        sectionId = window.document.getElementById('Section1');
                    }
                    .moveToObject('#ribbon-radio-tile')
                    .buttonDown()
                    .moveToObject(sectionId) -- -- > errors out here
                    .buttonUp()
                    .pause(2000)
                    .end()
                });

这就是for仅在内部for(i=0; i<4; i++) { for(j=0; j<5; j++) { System.out.print(twoD[i][j] + " "); } System.out.println(); } 循环之后执行的原因。