如何操作嵌套for循环

时间:2013-11-28 14:24:53

标签: java multidimensional-array nested-loops

String[][] board = [a,b,c,d]
                   [e,f,g,h];   

for(int i=0; i<board.length; i++){
    String temp = "";
    for(int j=0; j<board[i].length; j++){
        temp = temp+board[i][j];
        System.out.println(temp);
    }
}

当前输出

a
ab
abc
abcd
e
ef
efg
efgh

我希望输出看起来像

a
ab
abc
abcd
b
bc
bcd
c
cd
d
e
ef
efg
efgh
f
fg
fgh
g
gh
h 

我该怎么做?

1 个答案:

答案 0 :(得分:1)

您需要第三个嵌套for循环来执行此操作:

String[][] board = [a,b,c,d]
                   [e,f,g,h];   

// i - for each row
for(int i=0; i<board.length; i++){

    // j - start from this column in a row
    for(int j=0; j<board[i].length; j++){
        String temp = "";        
        // put all columns right to the j and including together
        for(int k=j;k<board[i].length; k++) {
            temp = temp+board[i][k];
            System.out.println(temp);
        }
    }
}