Explicitly assigning values to a 2D Array?

后端 未结 6 666
遇见更好的自我
遇见更好的自我 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.

    0 讨论(0)
  • 2020-12-11 01:29

    Is this what you mean?

    int contents[][] = new int[2][2];
    contents[0][0] = 1;
    contents[1][1] = 2;
    ...
    

    That will let you individual assign values to elements in your 2D array, one at a time.

    Also note that you cannot access index 2 in an array of size 2. An array of size 2 has 2 valid indicies (0 and 1). In general, an array of size N has N valid indicies (0...(N-1))

    0 讨论(0)
  • 2020-12-11 01:30

    Are you looking to assign all values in a 2D array at declaration time? If so, it works as follows:

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

    Remember that a 2D array in Java is really an array of arrays, but Java gives you some special syntax if you do this at declaration time.

    0 讨论(0)
  • 2020-12-11 01:31

    Looks like you want to assign a row in one statement?

    After declaration like:

    int[][] matrix = new int[2][2] //A
    

    or

    int[][] matrix = new int[2][] //B
    

    You can use two kinds of assignment statement:

    matrix[0][0]=1; //can only used in A, or will throw the NullPointerException.
    
    matrix[1]=new int[] {3,3,5};//This can be used both in A and B. In A, the second row will have 3 elements.
    
    0 讨论(0)
  • 2020-12-11 01:37

    contents[0][0] points to a single int, not an array of ints. You can only assign a single value to any particular index into the array.

    0 讨论(0)
  • 2020-12-11 01:40

    You want this:

    int [][] t = {{1,2,3},{4,5,6}};
    
    0 讨论(0)
提交回复
热议问题