简体   繁体   English

3D 数组赋值

[英]3D array assigning values

Can I use the following format to simplify assigning values in java to a 3D array if possible then how?如果可能的话,我可以使用以下格式来简化将 java 中的值分配给 3D 数组吗?

    int [][][]array = new int[3][][];

    array[0] = new int [4][5];
    array[1] = new int [5][5];
    array[2] = new int [3][5];


    array[0] = {{1,2,3,4,5} , {1,2,3,4,5} , {1,2,3,4,5} , {1,2,3,4,5}};
    array[1] = {{1,2,3,4,5} , {1,2,3,4,5} , {1,2,3,4,5} , {1,2,3,4,5}, {1,2,3,4,5}};
    array[2] = {{1,2,3,4,5} , {1,2,3,4,5} , {1,2,3,4,5}};

The simplest and cleanest way to assign this type of data -- put the data into a file, here a text file would be adequate, and then read it in using nested for loops.分配这种类型数据的最简单和最干净的方法——将数据放入一个文件中,这里一个文本文件就足够了,然后使用嵌套的 for 循环读取它。 This avoids hard-coding the data, and makes it easy to change the data without having to change the code.这避免了对数据进行硬编码,并且无需更改代码即可轻松更改数据。

You can do it like this:你可以这样做:

int[][][] array = {
        {{1,2,3,4,5} , {1,2,3,4,5} , {1,2,3,4,5} , {1,2,3,4,5}},
        {{1,2,3,4,5} , {1,2,3,4,5} , {1,2,3,4,5} , {1,2,3,4,5}, {1,2,3,4,5}},
        {{1,2,3,4,5} , {1,2,3,4,5} , {1,2,3,4,5}},
};

Another alternative:另一种选择:

int[][] array1 = {{1,2,3,4,5} , {1,2,3,4,5} , {1,2,3,4,5} , {1,2,3,4,5}};
int[][] array2 = {{1,2,3,4,5} , {1,2,3,4,5} , {1,2,3,4,5} , {1,2,3,4,5}, {1,2,3,4,5}};
int[][] array3 = {{1,2,3,4,5} , {1,2,3,4,5} , {1,2,3,4,5}};
int[][][] array = {array1, array2, array3};

The initializer expression {...} can only be used at declaration time.初始化表达式{...}只能在声明时使用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM