简体   繁体   English

初始化二维数组

[英]initialize two dimensional array

I am trying to initialize below map as 2D array but somehow I am not able to understand how can I initialize below map in 2D array. 我正在尝试将地图下方的地图初始化为2D数组,但以某种方式,我无法理解如何在2D数组地图的下方进行初始化。 Somehow from the graph it is looking pretty confusing. 从图中以某种方式来看,它看起来很混乱。 Below is the graph: 下图是:

在此处输入图片说明

Is this the right way to do it? 这是正确的方法吗?

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 } };

What's confusing about: 令人困惑的是:

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 } };

?

Probably the most flexible way to initialize and array like this is to store the data in a text file, something like so: 这样初始化和数组的最灵活的方法可能是将数据存储在文本文件中,如下所示:

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

And then read in the data, and initializing your array from the data. 然后读入数据,并根据数据初始化数组。 This allows you to more easily change the data without having to change your program. 这使您可以更轻松地更改数据,而不必更改程序。

Yes; 是; as long as it compiles, it is "correct". 只要编译,它就是“正确的”。 There are other ways to initialize this array but I am not really sure why this is confusing. 还有其他方法可以初始化此数组,但是我不确定为什么会造成混淆。

    // 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();
}

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

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