[英]Game of life neighbor issue. array index out of bounds exception
我正在研究生命游戲程序,我遇到了一個問題。
正如您在下面看到的,我正在嘗試計算鄰居的數量。
問題是,當計算位於設置網格邊界的坐標的鄰居數量時,給出了ArrayIndexOutOfBoundsException錯誤。
為了解決這個問題,我使用了try和catch。
唯一的問題是,只要編譯器檢測到ArrayIndexOutOfBoundsException,它就會直接傳遞給catch部分,而不是通過其他if語句。
有沒有辦法解決?
public int neighbours(int x, int y) {
int result = 0;
try {
if (life[y + 1][x - 1] == '*') {
result++;
}
if (life[y + 1][x] == '*') {
result++;
}
if (life[y + 1][x + 1] == '*') {
result++;
}
if (life[y][x + 1] == '*') {
result++;
}
if (life[y][x + 1] == '*') {
result++;
}
if (life[y - 1][x] == '*') {
result++;
}
if (life[y - 1][x - 1] == '*') {
result++;
}
if (life[y][x - 1] == '*') {
result++;
}
} catch (ArrayIndexOutOfBoundsException e) {
}
return result;
}
您可以在每個測試周圍放置一個單獨的try
/ catch
,以避免在其中一個引發異常時跳過其余部分,但更好的選擇是事先檢查數組的邊界值。 或者你可以讓數組在每個邊上都有一個未使用的額外行或列,然后不檢查實際使用的單元格是否超出邊界。
試試這個:方法很容易維護,減少重復代碼!
public int neighbours(int x, int y) {
int result = 0;
for(int i=x-1; i<=x+1;i++){
if(i<life.length && i>0){
for(int j=y-1; j<=y+1;j++){
if(j<life[i].length && j>0){
if (life[i][j] == '*') {
result++;
}
}
}
}
}
return result;
}
改進Hache的代碼:
public int neighbours(int x, int y) {
int result = 0;
for(int i=x-1; i<=x+1;i++){
//include border cell, so i>=0
if(i<life.length && i>=0){
for(int j=y-1; j<=y+1;j++){
//again, include border cell, so j>=0
if(j<life[i].length && j>=0){
//and to compare strings, please use equals()
if (life[i][j].equals("*")) {
result++;
}
}
}
}
}
//don't count the cell itself
return result - 1;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.