views:

206

answers:

2

I have a class, "Tetris", in which one of the instance variables is "board". "board" is 2D array of Color objects. Upon the creation of a tetris object I call a method that sets the dimensions of board and then sets all of the Color objects to be the Default value, that is to say, Color.blue.

public Tetris(int rows, int cols) {
  this.rows = rows;
  this.cols = cols;
  reset(rows, cols);
}

public void reset(int rows, int cols) {
  Color[][] board = new Color[rows][cols];
  for(int i  = 0; i<this.rows; i++) {
    for(int j  = 0; j<this.cols; j++) {
      board[i][j] = DEFAULT_COLOR; //  Color.blue; //DEFAULT-COLOR
    }
  }
}

Unfortunately, when I run the code (which obviously has not been posted in its entirety) I get a null pointer exception on the line:

board[i][j] = DEFAULT_COLOR; //  Color.blue; //DEFAULT-COLOR.

Is there anything obviously wrong with what I am doing?

A: 

I think you must allocate every one of those colors like this: board[i][j] = new Color(...

SurvivalMachine
There's no need for that - using DEFAULT_COLOR will just mean each array element refers to the same object. In particular, that wouldn't cause a NullPointerException in the assignment.
Jon Skeet
+2  A: 

It would help if you would post a short but complete program which demonstrated the problem. The code you've posted isn't enough to throw an exception, but I can see how with a few changes it might.

In particular, it seems odd to me that you're declaring a new local variable within your reset method... and you also have an instance variable called board? I suspect the solution may be as simple as changing the start of reset to:

board = new Color[rows][cols];

If your real code uses the local variable to create the array, but then tries to assign values via the instance variable, that could very well be the cause of the problem.

It also seems wrong that you're passing rows and cols into the method, and using those parameters in one place but the instance variables this.rows and this.cols in the loop. Why bother passing them at all?

Jon Skeet