I am trying to create this game https://en.wikipedia.org/wiki/Conway's_Game_of_Life, however, whenever I am trying to use the printBoard method, I get the following error
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 5 out of bounds for length 5.
How can I fix this issue? Thanks
public class Board {
final int[][] board;
final int width;
final int height;
public Board(int width, int height) {
this.width = width;
this.height = height;
this.board = new int[width][height];
}
public void printBoard() {
System.out.println("---");
for (int i = 0; i < height; i ) {
String line = "|";
for (int j = 0; j < width; j ) {
if (this.board[i][j] == 0) {
line = ".";
} else {
line = "*";
}
}
line = "|";
System.out.println(line);
}
System.out.println("---\n");
}
public int countAliveNeighbours(int x, int y) {
int count = 0;
count =this.board[x-1][y-1];
count =this.board[x][y-1];
count =this.board[x 1][y-1];
count =this.board[x 1][y];
count =this.board[x 1][y 1];
count =this.board[x][y 1];
count =this.board[x-1][y 1];
count =this.board[x-1][y];
return count;
}
public void setAlive(int x, int y) {
this.board[x][y] = 1;
}
}
CodePudding user response:
Board initialisation is
this.board = new int[width][height];
Make it to:-
this.board = new int[height][width];
or change the loop where you are iterating height with width.