简体   繁体   中英

How to manipulate nested for 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);
    }
}

Current output

a
ab
abc
abcd
e
ef
efg
efgh

I want the output to look like

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

How would I do this?

You need a third nested for loop to do that:

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

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