Explicitly assigning values to a 2D Array?

后端 未结 6 665
遇见更好的自我
遇见更好的自我 2020-12-11 00:58

I\'ve never done this before and can\'t find the answer. This may not be the correct data type to use for this, but I just want to assign an int, then another int without a

6条回答
  •  臣服心动
    2020-12-11 01:16

    The best way is probably to just declare and assign all values at once. As shown here. Java will automatically figure out what size the array is and assign the values to like this.

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

    Alternatively if you need to declare the array first, remember that each contents[0][0] points to a single integer value not an array of two. So to get the same assignment as above you would write:

    contents[0][0] = 1;
    contents[0][1] = 2;
    contents[1][0] = 4;
    contents[1][1] = 5;
    

    Finally I should note that 2 by 2 array is index from 0 to 1 not 0 to 2.

    Hope that helps.

提交回复
热议问题