【问题标题】:How to manipulate nested for loops如何操作嵌套的for循环
【发布时间】:2013-11-28 14:24:53
【问题描述】:
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 

我该怎么做?

【问题讨论】:

  • 您是否尝试过单步执行您的代码,看看会发生什么?也许这会给你一个提示,为什么你的代码没有产生你想要的输出。
  • 您也可以尝试使用纸和铅笔来校对您的算法草图。

标签: java multidimensional-array nested-loops


【解决方案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);
        }
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-12-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-13
    相关资源
    最近更新 更多