Game of Life ArrayIndexOutofBounds

前端 未结 2 419
再見小時候
再見小時候 2021-01-27 07:32

I\'m doing the Conway\'s game of life. I\'m pretty sure I\'m close to finished, but when I run it, I get Exception in thread \"main\" java.lang.ArrayIndexOutOfBoundsExcep

2条回答
  •  难免孤独
    2021-01-27 07:53

    When r is 0, this one is not valid: old[r - 1][c].
    Thus you get the exception you posted.

    I suggest you simplify it like this.

        boolean isValidPosition(int r, int c){
            return 
                0 <= r && r < N &&
                0 <= c && c < M;
    
        }
    
        int getNeighboursCount(boolean[][] old, int r, int c){
            int neighbors = 0;
            for (int i=-1; i<=1; i++){
                for (int j=-1; j<=1; j++){
                    if (i!=0 || j!=0){
                        if (isValidPosition(r + i, c + j)){
                            if(old[r + i][c + j])
                            {
                                neighbors++;
                            }
                        }
                    }
                }
            }
            return neighbors;
        }
    

提交回复
热议问题