java - 18x18 Board Array Index Out of Bounds -


// counts neighbors of alive or dead cells in boolean grid.     public static int countneighbors ( final boolean[][] grid, final int row, final int col ) {         // finds neighbors in top row.         int count = 0;         (int = 1; > -1; --i) {             if (grid[row - 1][col + i] == true)                  count += 1;             else if (grid[row - 1][col + i] == false)                 count += 0;         }          // finds neighbors in same row.         (int = 1; > -1; --i) {             if (grid[row][col + i] == true)                  count += 1;             else if (grid[row][col + i] == false)                 count += 0;         }          // finds neighbors in bottom row.         (int = 1; > -1; --i) {             if (grid[row + 1][col + i] == true)                 count += 1;             else if (grid[row + 1][col + i] == false)                 count += 0;         }          return count;     } 

getting array out of bounds exception when attempt find true neighbor values in 8 blocks around specified square.

i figured code handle if out of bounds assume values false anyways.

create separate function grid cell, including bounds check:

public static boolean getgridcell ( final boolean[][] grid, final int row, final int col ) {      // bounds check:      if((row < 0) || (row >= grid.length))          return false;      if((col < 0) || (col >= grid[row].length))          return false;       return grid[row][col]; } 

then call function instead of accessing grid directly:

public static int countneighbors ( final boolean[][] grid, final int row, final int col ) {     // finds neighbors in top row.     int count = 0;     (int = 1; >= -1; --i) {         if (getgridcell(grid, row - 1,col + i))              count += 1;     }      // finds neighbors in same row.     (int = 1; >= -1; --i) {         if (getgridcell(grid, row, col + i))              count += 1;     }      // finds neighbors in bottom row.     (int = 1; >= -1; --i) {         if (getgridcell(grid, row + 1, col + i))             count += 1;     }      return count; } 

also:

  • there's no need check if grid cell empty , add 0 count if is, because isn't going make difference count.
  • you don't need test if(some_boolean == true), can write if(some_boolean)
  • your loop termination condition should >= -1 not > -1, if intend include -1.

Popular posts from this blog

c# - ODP.NET Oracle.ManagedDataAccess causes ORA-12537 network session end of file -

matlab - Compression and Decompression of ECG Signal using HUFFMAN ALGORITHM -

utf 8 - split utf-8 string into bytes in python -