Skip to content
Advertisement

Game Of Life game: Check 2D array 8 closest surroundings; ArrayIndexOutOfBoundsException issue

I have encountered this problem and i couldn’t find the solution. There is a 2D array with only zeros and ones in it (the size of the array doesnt really matter, i worked with 10×10). Zero means dead and 1 is alive. I double for looped this to check the elements sorroundings and when it sorrounded with other “cells” the code would work fine. But when its in the corner or one of the other edge of the array then it throws an ArrayIndexOutOfBoundsException. My question is how to write a code for this without handle all the possible situation?

JavaScript

}

JavaScript

}

Advertisement

Answer

In the numberOfAliveNeighbours method, you have to test for an array index less than zero or greater than the size of the array – 1.

In other words, an int array 8 values long has index values from 0 – 7.

Here’s your code fixed up.

JavaScript
Advertisement