简体   繁体   中英

Null pointer exception error using a 2d object array

I am having a problem. I have a class called Space. private spaceColour colour;

public class Space {

public enum spaceColour{
    Black, White, Null;
}

private spaceColour colour;

public Space (spaceColour colour)
{
    this.setColour(colour);
}

public spaceColour getColour() {
    return colour;
}

public void setColour(spaceColour colour) {
    this.colour = colour;
}

}

Using Space, I create a 2d array of this object, in this method

public void testMethods()
  {
   Space[][] test = new Space[2][2];
LINE:252   test[0][0].setColour(spaceColour.Black);
   test[0][1].setColour(spaceColour.Black);
   test[1][0].setColour(spaceColour.Black);
   test[1][1].setColour(spaceColour.Black);

   ThreeinaRow(test);

   for(int row= 0; row<test.length;row++)
   {
       for(int column = 0; column<test.length;column++)
       {
           if (test[row][column].getColour().equals(spaceColour.White))
           {
               System.out.println("Whites at row:" + row + "Column: "+ column);
           }
       }
   }
 }

The three in a row method basically adds on spaces with a particular colour.

I'm getting a Null pointer exception at line 252 as indicated. I really don't understand why, any help would be appreciated.

you've instantiated the array, but not the objects.

test[0][0] = new Space();
test[0][0].setColour(spaceColour.Black);
test[0][1] = new Space();
test[0][1].setColour(spaceColour.Black);
test[1][0] = new Space();
test[1][0].setColour(spaceColour.Black);
test[1][1] = new Space();
test[1][1].setColour(spaceColour.Black);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM