初始化二维数组

时间:2015-10-25 01:33:34

标签: java arrays multidimensional-array

我正在尝试将下面的地图初始化为二维数组但不知何故我无法理解如何在二维数组中初始化下面的地图。不知何故,从图表看起来很混乱。下面是图表:

enter image description here

这是正确的方法吗?

byte graph[][] = { { 0, 0, 0, 1, 0, 0, 0, 0 }, { 0, 0, 1, 1, 0, 0, 0, 0, }, { 0, 0, 0, 0, 0, 0, 0, 0 },
        { 0, 0, 0, 0, 1, 1, 1, 0 }, { 1, 1, 0, 0, 0, 0, 0, 0 }, { 0, 0, 1, 0, 0, 0, 0, 0 } };

3 个答案:

答案 0 :(得分:2)

令人困惑的是:

0 0 0 1 0 0 0 0
0 0 1 1 0 0 0 0
0 0 0 0 0 0 0 0 
0 0 0 0 1 1 1 0
1 1 0 0 0 0 0 0
0 0 1 0 0 0 0 0

这种初始化和数组最灵活的方法可能是将数据存储在文本文件中,如下所示:

CREATE TABLE `wp_posts` (
  `Id` INT(11) PRIMARY KEY,
  `img_id` VARCHAR(100) UNIQUE NOT NULL
);
CREATE TABLE `wp_posts_thumbs` (
  `Id` INT(11) PRIMARY KEY,
  `img_id` VARCHAR(100) UNIQUE NOT NULL,
  `post_parent` INT(11)
);

INSERT INTO wp_posts (id,img_id) VALUES (1,'aiec');
INSERT INTO wp_posts (id,img_id) VALUES (2,'mucl');
INSERT INTO wp_posts (id,img_id) VALUES (3,'da85');
INSERT INTO wp_posts_thumbs (id,img_id,post_parent) VALUES (101,'aiec',0);
INSERT INTO wp_posts_thumbs (id,img_id,post_parent) VALUES (102,'mucl',0);
INSERT INTO wp_posts_thumbs (id,img_id,post_parent) VALUES (103,'da85',0);

UPDATE wp_posts_thumbs 
    LEFT JOIN wp_posts 
        ON wp_posts_thumbs.img_id = wp_posts.img_id 
    SET post_parent = wp_posts.id 
    WHERE wp_posts_thumbs.img_id = wp_posts.img_id; 

然后读入数据,并从数据初始化数组。这使您可以更轻松地更改数据,而无需更改程序。

答案 1 :(得分:0)

是;只要它编译,它就是“正确的”。 还有其他方法来初始化这个数组,但我不确定为什么这会令人困惑。

答案 2 :(得分:0)

    // Create new 2-dimensional array.
int[][] values = new int[6][8];

// Assign elements within it.
values[0][3] = 1;
values[1][2] = 1;
values[1][3] = 1;
values[3][4] = 1;
values[3][5] = 1;
values[3][6] = 1;
values[4][0] = 1;
values[4][1] = 1;
values[5][2] = 1;
// Loop over top-level arrays.
for (int i = 0; i < values.length; i++) {

    // Loop and display sub-arrays.
    int[] sub = values[i];
    for (int x = 0; x < sub.length; x++) {
    System.out.print(sub[x] + " ");
    }
    System.out.println();
}