[英]Array index out of bounds exception -1
我現在要在40分鍾內完成此作業...我將其提交給此在線商品,它會測試方法等,並且出現此錯誤。 我知道什么是越界,但是我不明白它所指定的代碼在哪里發生:
public int countNeighbours(int x, int y) {
int neighbourCount = 0;
for (int i = 0; i < cells.length; i++) {
for (int j = 0; j < cells.length; j++) {
if ((cells[x][y].isAlive() == true) && (x < cells.length) && (y < cells.length) && (x >= 0)
&& (y >= 0)) {
neighbourCount++;
}
else if ((cells[x][y].isAlive() == false) && (x < cells.length) && (y < cells.length) && (x >= 0)
&& (y >= 0)) {
neighbourCount--;
}
else if (!(x < cells.length) || !(y < cells.length) || !(x >= 0) || !(y >= 0)) {
return 0;
}
else {
neighbourCount = neighbourCount;
}
}
}
return neighbourCount;
}
我不知道它是否真的有效,我為此使用了不同的代碼,但是有問題。
無論如何,在線事物基本上會測試無效坐標,並確保我的代碼為無效坐標返回正確的值(即返回0)。
所以我不知道為什么會出現超出范圍的錯誤,我覺得我已經完全指定了范圍。
我還有一個子問題,它在單元有8個鄰居的測試中也失敗了,但是我的代碼返回-9。 所以很明顯,它只經過返回neighbourCount的那一個,但是我真的不明白為什么。 我是否錯過了規格中的某些內容? 也許它與我的代碼完全不同的部分有關。
表達式是從左到右計算的,因此在訪問cell[x][y]
之前,應檢查x
和y
的值是否在有效范圍內:
if ((x < cells.length) && (y < cells.length) && (x >= 0)
&& (y >= 0) && (cells[x][y].isAlive() == true))
順便說一句,該測試假設cells
是一個正方形矩陣(即它具有相同數量的列和行)。
PS,不清楚為什么要遍歷i
和j
,然后在循環中根本不使用它們。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.