-1

I have a problem with my loop, it must be a basic fix but i cant seem to fix this issue, this is a 2D array that i am checking the neighbours of a grid for , now

if randomGrid [rows -1] and [col] == 1 , this means the cell that is on the left of the current cell on the x Axis

for(int rows = 0 ; rows < randomGrid.length ; ++rows){
        for(int cols = 0 ; cols < randomGrid.length ; ++cols){

            //all 8 neighbours 
             if(randomGrid[rows-1][cols] == 1){
                 neighbours++;
             }
             if(randomGrid[rows-1][cols-1] == 1){
                 neighbours++;
             }

error:

 Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: -1
 at Control.count(Control.java:196)
 at Control.main(Control.java:247)
tim smith
  • 44
  • 8

1 Answers1

0
randomGrid[rows-1][cols]

is -1 when row is zero

So you need to make that lines

randomGrid[rows][cols]
smttsp
  • 4,011
  • 3
  • 33
  • 62
  • 1
    Actually, `int rows = 1` would make more sense than this – OneCricketeer Mar 13 '17 at 23:04
  • @cricket_007 I think s/he has `row+1` too inside for loop. The code is not finished, so s/he just need to be careful in either case. But I agree, it might be easier for the OP. – smttsp Mar 13 '17 at 23:10