假設有newTable[5][6]
,2D陣列
int[][] newTable = {{1, 2, 3, 4, 5},
{6, 7, 8, 9, 8},
{7, 6, 5, 4, 3},
{2, 1, 2, 3, 4},
{5, 6, 7, 8, 9},
{8, 7, 6, 5, 4}};
當循環通過它們
for (int i = 0; i < 5; i++) {
for (int j = 0; j < 6; j++) {
}
}
在外環的5
導致循環運行5次。對於這些迭代中的每一個,都存在比運行6
次更多的循環,總計5 * 6
次(30)
。
i
和j
如果您想使用循環中的索引,則i
和j
表示索引。
//例如 newTable [i] [j] = 1; //我和j是第一次迭代,所以我= 0和j = 0
如果你看看我的矩陣上面,你會看到左上角,你會看到值1
。 newTable[i][j] = 1;
中的i
代表"rows"
和j
代表"column"
。 rows
在這種情況下實際上是下降和columns
去橫跨。
所以,如果你說
inx x = newTable[3][4];
x
就等於4
,因爲你去3
下降(從0開始)和4
翻過(從0 atarting)
讓我們回到循環。我可能不會回答你的問題,但我想給你一些見解。
for (int i = 0; i < 5; i++) {
for (int j = 0; j < 6; j++) {
// say you have another table "table"
table[i][j] = newTable[i][j]
}
}
以上所做的全部工作都是將值爲table[i][j] = newTable[i][j]
。如果你想交換他們,你可以這樣做
for (int i = 0; i < 5; i++) {
for (int j = 0; j < 6; j++) {
int temp = newTable[i][j];
table[i][j] = newTable[i][j];
newTable[i][j] = table[i][j];
}
}
我喜歡,我說,我可能不會回答你的問題。但我想指出的一件事是,你是玩弄指數,你很有可能得到一個錯誤消息,稱爲Excpetion
。有很多不同種類的Exceptions
。在循環播放指數的情況下,很有可能獲得和ArrayIndexOutOfBoudsException
。它正是它的樣子。這意味着,您試圖訪問[5][6]
範圍以外的index
。
例如,如果在你的循環,你有這樣的事情
newTable[i + 1][j] = table[i][j];
和循環是在它的最後一次迭代,這是i = 4
和j = 5', you would get an
ArrayIndexOutOfBoundsExeption because you're trying access
newtable的[5] [5]`這不存在。
至於你的問題,關於這個
newTable.setLetter(0,5,Table[0][2]);
我不知道該怎麼赫克,做,沒有看到更多的代碼。但是你的邏輯聽起來是正確的,因爲正確實施,如果setLetter()
甚至存在。
什麼是新表? – Taylor
newTable是一個新的多維數組。完整的算法將一個表格的內容應用到另一個表格,並將其應用到另一個表格中,類似於副本 –
[SSCCE](http://sscce.org)將爲您提供更多的關注和更好的答案。 –