0

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.

0

1 Answer 1

2

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);
Sign up to request clarification or add additional context in comments.

5 Comments

+1 Also test[0][0] = new Space(spaceColour.Black); would work as there is a constructor with that signature in his class.
Is there any way to intitialise say a 4x4 Space array, where all of the Spaces are already initialised to spaceColour.Null?
Try this: Arrays.fill(test, new Space()); put it after the line where you declare it, but before you then access the array
Do you mean Arrays.fill(test,new Space(spaceColour.Null)); ?
bloody constructor! :p

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.