java - ArrayOutofBounds Exception even though it checks if the square is on the edge -
this code part of code conway's game of life simulation. particular method 'step', advancing game forward 1 generation. there seems error when attempts check if square straight true or false (this 10 x 10 boolean array @ moment). code's intention check every square , count how many neighbors each square has. have if statements making squares on edges , corners go under special conditions (e.g. 1 in top right doesn't check squares straight up, top right, , directly right)
exception in thread "awt-eventqueue-0" java.lang.arrayindexoutofboundsexception: 10 @ life.step(life.java:71)
the error above , line 71 if statement checks neighbor straight down
public void step() { system.out.println("step"); system.out.println(cells.length); system.out.println(cells[0].length); boolean[][] nextcells = new boolean[cells.length][cells[0].length]; (int row = 0; row < cells.length; row++) { (int col = 0; row < cells[0].length; col++) { int neighborcount = 0; // checks neighbor straight down if (row > 0 && cells[row - 1][col] == true) { neighborcount++; } // lower right if (row > 0 && col < cells[0].length - 1 && cells[row - 1][col + 1] == true) { neighborcount++; } // right if (col < cells[0].length - 1 && cells[row][col + 1] == true) { neighborcount++; } // upper right if (row < cells.length - 1 && col < cells[0].length - 1 && cells[row + 1][col + 1] == true) { neighborcount++; } // straight if (row < cells.length - 1 && cells[row + 1][col] == true) { neighborcount++; } // upper left if (row < cells.length - 1 && col > 0 && cells[row + 1][col - 1] == true) { neighborcount++; } // left if (col > 0 && cells[row][col - 1] == true) { neighborcount++; } // lower left if (row > 0 && col > 0 && cells[row - 1][col - 1]) { neighborcount++; }
look @ line above error being thrown:
for (int col = 0;
row
< cells[0].length; col++) {
this should be:
for (int col = 0;
col
< cells[row].length; col++) {
Comments
Post a Comment