Reputation: 39
I'm working on the standard Game Of Life program for my Intro to Java course, and so far I've been able to accomplish a lot of it on my own. However, I'm having some difficulty with counting the neighbors of a given cell, to determine whether it lives or dies.
Here is my countNeighbors
method:
public static int countNeighbors(int [][] board, int A, int B)
{
int [][]a = board;
int count = 0;
if (a[A][B] == 0 || a[A][B] == 1) {
try{
if (a[A-1][B-1] == 1) {count++;}
if (a[A ][B-1] == 1) {count++;}
if (a[A+1][B-1] == 1) {count++;}
if (a[A-1][B ] == 1) {count++;}
if (a[A+1][B ] == 1) {count++;}
if (a[A-1][B+1] == 1) {count++;}
if (a[A ][B+1] == 1) {count++;}
if (a[A+1][B+1] == 1) {count++;}
}
catch (ArrayIndexOutOfBoundsException e) {}
}
return count;
}
When I run my program, this method does not count the neighbors correctly, thus initializing an incorrect new generation. How do I overcome the out of bounds indices of an array?
Upvotes: 0
Views: 217
Reputation: 393986
You should check that A
and B
fall within the bounds of the board
array. Then you should check that adding or subtracting 1 to A
or B
keeps you within the bounds of the array.
For example:
if (A < a.length && B < a[A].length) {
if (a[A][B] == 0 || a[A][B] == 1) {
if (A > 0 && B > 0)
if (a[A-1][B-1] == 1) {count++;}
....
if (A+1 < a.length && B+1 < a[A].length)
if (a[A+1][B+1] == 1) {count++;}
}
}
Upvotes: 1