简体   繁体   中英

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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