java - change array
OK let's say I have this array:
public int[][] loadBoard(int map) {
if (map == 1) { return new int[][] {
{2,开发者_开发百科2,24,24,24,24,24,1,3,0,0,0,1 }, {
2,2,24,23,23,23,24,1,3,0,0,0,1 }, {
1,1,24,23,23,23,24,1,3,3,3,3,1 }, {
1,1,24,24,23,24,24,1,1,1,1,3,1 }, {
1,1,1,1,7,1,1,1,1,1,1,3,1 }, {
6,1,1,1,7,7,7,7,7,1,1,1,1 }, {
6,3,3,1,3,3,3,1,7,7,7,3,1 }, {
6,72,3,3,3,1,1,1,1,7,7,1,1 }, {
3,3,3,3,1,1,1,1,1,1,7,1,1 } }; } }
return board;
and I can call it doing this:
board = loadBoard(1);
But... let's say I want to change the number 72 on map 1 array (bottom-left in the array) to the number... 21. Can you do that?
board[7][1] = 21;
Explanation: When dealing with an array a[]
, a[n]
references the (n+1)th element (keeping in mind the first element is a[0]
.
A multidimensional array is just an array of arrays. So if you have a 2D array b[][]
, then b[n]
references the (n+1)th array.
Your value 72 is in the 8th array (index 7), at the 2nd position (index 1). Therefore board[7][1]
references that value, and board[7][1] = 21
assigns it the value 21.
Aside: Sometimes (usually, even) you don't know when you write the code which indexes you want to work with, (say you want to do it generically for all maps). This code will find all occurrences of 72
and replace them with 21
:
int numToReplace = 72;
int replacement = 21;
//loop through each nested array
for ( int i = 0; i < board.length; i++ ) {
//loop through each element of the nested array
for ( int j = 0; j < board[i].length; j++ ) {
if ( board[i][j] == numToReplace ) {
board[i][j] = replacement;
}
}
}
When you declare an array like int[][], you use two indexes to identify a single value in the two-dimensional array.
When initialized like
int[][] myarray = {
{ a,b,c,d,... }, // 0
{ a,b,c,d,... }, // 1
{ a,b,c,d,....} // 2
};
The first index selects one of the nested arrays. (0, 1 or 2) in the example. The second index then selects an item from the nested array, a,b,c,d... above.
The indexes always start from 0: myarray[0][0] gives the value stored in array 0, position a. myarray[1][3] gives the value 'd' from nested array 1.
In your example, the number 72 was in the 8th array, second position, counting using natural numbers (from 1). But since indexes start from 0, this becomes index [7][1]. Which is the answer.
board[7][1] = 72;
精彩评论