-1

需要输出到我之前关于 3d 数组声明的帖子,在 3D 数组声明时出错。我想首先获得所有第一个元素的输出,第二个元素的输出,依此类推。但目前我正在了解尺寸。有人可以帮我找到正确的方法吗?这是我的示例代码:

Integer[][][] _3D = new Integer[][][]{{{1,2,3},{4,5,6},{7,8,9},{2,4,5}},{{1,2,3},{4,5,6},{7,8,9},{2,4,5}}}; // it should be like this.


for (Integer[][] d3 : _3D) {
    for (Integer[] d2 : d3) {
        for (Integer d : d2) {
            System.out.print(d+"\t");  
                          // Expecting 1,4,7,2,1,4,7,2,2,5,8,4,2,5,8,4,3,6,9,5,3,6,9,5
            }
    }
}
4

4 回答 4

3

In case you're sure your innermost array always has a length of three, you can do the following:

for(int i = 0; i < 3; i++) {
    for (Integer[][] d3 : _3D) {
        for (Integer[] d2 : d3) {
            System.out.print(d2[i]);
        }
    }
}

Btw.: Why do you use an Integer[][][] instead of int[][][]?

于 2013-11-14T08:31:15.993 回答
0
        for(int i=0;i<_3D[0][0].length;i++){
        for(int[][]_2D : _3D){
            for(int[] _1D : _2D){
                System.out.print(_1D[i]);
            }
            System.out.println("*****");
        }
    }
于 2013-11-14T09:25:14.687 回答
0

如果你想要所有索引 0,然后所有索引 1,等等,你不能使用 foreach,它迭代单个数组的元素。

相反,试试这个:

for (Integer[][] d3 : _3D) 
    for (int i = 0; i < d3[0].length; i++) 
        for (int j = 0; j < d3.length; j++) 
            System.out.print(d3[j][i]+"\t");  

请注意两个内部循环的“倒置”嵌套。

于 2013-11-14T08:23:47.790 回答
0

试试这个代码:

     Integer[][][] _3D = new Integer[][][]{{{1,2,3},{4,5,6},{7,8,9},{2,4,5}},{{1,2,3},{4,5,6},{7,8,9},{2,4,5}}}; // it should be like this.


    //Expecting 1,4,7,2,1,4,7,2,2,5,8,4,2,5,8,4,3,6,9,5,3,6,9,5

    //Assume length are equal
    int length = _3D[0][0].length;

    for(int currColumn = 0; currColumn<length; currColumn++)
    {
        for (Integer[][] d3 : _3D) {

            for(int i =0; i<d3.length; i++)
            {
                System.out.print(d3[i][currColumn] +",");
            }

        }
    }

//期望 1,4,7,2,1,4,7,2,2,5,8,4,2,5,8,4,3,6,9,5,3,6,9,5

控制台中的输出:

        1,4,7,2,1,4,7,2,2,5,8,4,2,5,8,4,3,6,9,5,3,6,9,5,
于 2013-11-14T08:48:16.813 回答