bov25
bov25

Reputation: 121

2d array of 2 numbers in Java

Edit: Maybe it's a 3d array? I don't want to use ArrayList.

I know this is basic but I'm still having trouble wrapping my head around arrays. So I want to create a 2d array with 7 rows and 4 columns, like this:

  0 1 2 3
0        
1        
2        
3 
4
5
6

And in each spot I want to put two numbers. For example,

   0        1        2        3
0 (1, 8)   (2, 7)   (3, 6)   (4, 5)      
1        
2        
3 
4
5
6

Just as an example, if I was trying to fill (2,5) in it all in via for loops, I would do:

int[][][2] table = new int[7][4][2];
for (int i = 0; i < 7; i++) {
    for (int j = 0; i < 4; j++) {
    table[i][j][1] = 2;
    table[i][j][2] = 5;
    }
}

This isn't right. I can't figure out how to do it. Also, how would I reference a specific cell when it is correct? Like in the first example, if I wanted (1,8), would I put: table[1][1]? Or if I wanted just the 1 would I put: table[1][1][1]?

Upvotes: 1

Views: 88

Answers (1)

Andreas
Andreas

Reputation: 159086

You have 3 errors in your code:

int[][][2] table = new int[7][4][2]; // <== Remove 2
for (int i = 0; i < 7; i++) {
    for (int j = 0; i < 4; j++) {    // <== Change i to j
        table[i][j][1] = 2;          // <== Arrays are zero-based
        table[i][j][2] = 5;          // <== -
    }
}

Corrected code is:

int[][][] table = new int[7][4][2];
for (int i = 0; i < 7; i++) {
    for (int j = 0; j < 4; j++) {
        table[i][j][0] = 2;
        table[i][j][1] = 5;
    }
}

Testing with System.out.println(Arrays.deepToString(table)) produces:

[[[2, 5], [2, 5], [2, 5], [2, 5]], [[2, 5], [2, 5], [2, 5], [2, 5]], [[2, 5], [2, 5], [2, 5], [2, 5]], [[2, 5], [2, 5], [2, 5], [2, 5]], [[2, 5], [2, 5], [2, 5], [2, 5]], [[2, 5], [2, 5], [2, 5], [2, 5]], [[2, 5], [2, 5], [2, 5], [2, 5]]]

To update with the values given, you can replace the 3rd array, or update the values directly. Here I show both ways to update the first two:

int[][][] table = new int[7][4][2];

table[0][0] = new int[] { 1, 8 };

table[0][1][0] = 2;
table[0][1][1] = 7;
[[[1, 8], [2, 7], [0, 0], [0, 0]], [[0, 0], [0, 0], [0, 0], [0, 0]], [[0, 0], [0, 0], [0, 0], [0, 0]], [[0, 0], [0, 0], [0, 0], [0, 0]], [[0, 0], [0, 0], [0, 0], [0, 0]], [[0, 0], [0, 0], [0, 0], [0, 0]], [[0, 0], [0, 0], [0, 0], [0, 0]]]

You can even replace the entire first row in one operation:

int[][][] table = new int[7][4][2];
table[0] = new int[][] { {1, 8}, {2, 7}, {3, 6}, {4, 5} };
[[[1, 8], [2, 7], [3, 6], [4, 5]], [[0, 0], [0, 0], [0, 0], [0, 0]], [[0, 0], [0, 0], [0, 0], [0, 0]], [[0, 0], [0, 0], [0, 0], [0, 0]], [[0, 0], [0, 0], [0, 0], [0, 0]], [[0, 0], [0, 0], [0, 0], [0, 0]], [[0, 0], [0, 0], [0, 0], [0, 0]]]

Upvotes: 1

Related Questions