2010-07-14 133 views
1

OK讓我們說我有這樣的數組:爪哇 - 改變陣列

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; 

,我可以把它這樣做:

board = loadBoard(1); 

但是......比方說,我想更改號碼72在地圖1陣列(陣列中的左下角)到數字... 21.你能做到嗎?

回答

9
board[7][1] = 21; 

說明:當處理數組a[]a[n]引用第(n + 1)個元素(記住所述第一元素是a[0]

多維數組只是陣列。陣列。因此,如果有一個二維數組b[][],然後b[n]引用第(n + 1)個陣列

你的值72是第八陣列中(索引7),在第二位(索引1)。因此board[7][1]引用該值,board[7][1] = 21賦予它的價值21

除了:有時候(通常情況下,即使)你不要當你寫你要使用哪些索引的代碼知道,(說你要一般爲所有地圖做)。此代碼會發現所有出現7221替換它們:

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; 
     } 
    } 
} 
+0

你能否爲了他的緣故請你添加一些解釋? – 2010-07-14 13:35:20

+0

完成,謝謝@SB – 2010-07-14 13:50:43

+0

謝謝你 - 我只是不想你的正確答案被劫持:) – 2010-07-14 15:04:28

2

當你聲明如int [] [],您可以使用兩個索引的二維數組中找出一個值的數組。

當像

int[][] myarray = { 
{ a,b,c,d,... }, // 0 
{ a,b,c,d,... }, // 1 
{ a,b,c,d,....} // 2 
}; 

初始化的第一個索引選擇嵌套陣列中的一個。 (0,1或2)。第二個索引然後從嵌套數組a,b,c,d ...中選擇一個項目。

索引始終從0開始:myarray [0] [0]給出存儲在數組0中位置a的值。 myarray [1] [3]從嵌套數組1中給出值'd'。

在你的例子中,數字72在第8個數組中,第二個位置,使用自然數(從1開始)計數。但是由於索引從0開始,所以這成爲索引[7] [1]。這是答案。

board[7][1] = 72;