Game Of Life Java - Counting neighbors with 2D arrays and for loops -
i working on conway's game of life program in eclipse @test cases. of methods pass tests except neighborcount method. have seen posts of method working loops , reason not work on code.
i trying wrap around 2d array locating neighbor cells loops. having trouble updating new society after counting neighbors. if please take @ code , locate error in methods, appreciated. thank in advance. have attached of code in case have error in method affecting neighborcount().
public class gameoflife { private int therows; private int thecols; private char[][] society; public gameoflife(int rows, int cols) { // complete method. society = new char[rows][cols]; (int r = 0; r < rows; r++) { (int c = 0; c < cols; c++) { society[r][c] = ' '; } } therows = rows; thecols = cols; } public int numberofrows() { return therows; } public int numberofcolumns() { return thecols; } public void growcellat(int row, int col) { // complete method (int r = 0; r < society.length; r++) { (int c = 0; c < society[r].length; c++) { society[r][c] = 'o'; } } } public boolean cellat(int row, int col) { if (society[row][col] == 'o') { return true; } else { return false; } } @override public string tostring() { string res = ""; (int r = 0; r < society.length; r++) { (int c = 0; c < society[r].length; c++) res = res + society[r][c]; } return res; } public int neighborcount(int row, int col) { int count = 0; for(int = row - 1; <= row + 1; i++) { if (i >= 0 && >= society.length) for(int j = col - 1; j <= col + 1; j++) if (j >= 0 && j >= society[i].length) if (i != row || j != col) if (society[i][j] == 'o') count++; } return count; } public void update() { // complete method char[][] newsociety = new char[society.length][society[0].length]; (int r = 0; r < society.length; r++) { (int c = 0; c < society[r].length; c++) newsociety[r][c] = society[r][c]; } } }
looks have >= instead of < in 2 places :
public int neighborcount(int row, int col) { int count = 0; for(int = row - 1; <= row + 1; i++) { if (i >= 0 && < society.length) // fixed here for(int j = col - 1; j <= col + 1; j++) if (j >= 0 && j < society[i].length) // fixed here if (i != row || j != col) if (society[i][j] == 'o') count++; } return count; } if going access society[i][j], want make sure 0 <= < society.length , 0 <= j < society[i].length.
Comments
Post a Comment