猿问

JAVA特定于Array 2D的循环

我有这个数组:


 int[][] multi = new int[][]{

              { 3, 4, 2},

              { 2, 2, 5 },

              { 1, 2 }

            };

我想打印每个单元的产品。很难解释,所以让我们看一些例子:对于我的桌子,我需要打印:


        6 //(3*2*1)

        12 //(3*2*2)

        6 //(3*2*1)

        12 //(3*2*2)

        15 //(3*5*1)

        30 //(3*5*2)

        8 //(4*2*1)

        16 //(4*2*2)

        8 //(4*2*1)

        16 //(4*2*2)

        20 //(4*5*1)

        40 //(4*5*2)

...


表的大小可以改变,我需要一个通用的东西。


这是我的开始,但没有满足我的需要。这是逐行循环...


   for (int i = 0; i<multi[0].length; i++) {

           for (int k = 0; k < multi.length; k++) {

                for (int l = 0; l < multi[k].length; l++ ) {

                    System.err.println(multi[k][l]);

                }    

           }   

    }


慕森王
浏览 132回答 2
2回答

慕容708150

我的事情是,recursively如果数组的维数不固定,则必须这样做。我想出了动态维数的代码2D arraypublic class HelloWorld{&nbsp; &nbsp; static int[][] multi = new int[][]{&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; { 3, 4, 2},&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; { 2, 2, 5 },&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; { 1, 2 }&nbsp; &nbsp; };&nbsp; &nbsp; static public void pattern(int row,int multip) {&nbsp; &nbsp; &nbsp; &nbsp; if(row >= multi.length) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; System.out.println(multip);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return ;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; for(int i = 0; i<multi[row].length;i++) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; multip*=multi[row][i];&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; row+=1;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; pattern(row,multip);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; row-=1;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; multip/=multi[row][i];&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; public static void main(String []args){&nbsp; &nbsp; &nbsp; &nbsp; pattern(0,1);&nbsp; &nbsp; }}如果尺寸固定,则也可以使用上面的逻辑进行操作,但是如果要进行迭代,则必须在循环内部重复创建循环。
随时随地看视频慕课网APP

相关分类

Java
我要回答