0

In a checkers game for my CS class I have run into trouble with counting how many of a specific color piece are on the board. Here is the getter method:

 public int getCheckersBlue()
{
    int counter = 0;
    for(int x = 0; x <= 8; x++)
    {
        for(int y = 0; y <= 12; y++)
        {
            if(c[x][y].equals(Color.BLUE))
            {
                counter++;
            }
        }
    }
    return counter;
}

The constructor for c:

private CheckersBoard[][] c = new CheckersBoard[8][8];

Whenever trying to run the game in Greenfoot a null pointer exception is thrown even when the code compiles. Even with everything declared, everything has something it's pointing to. Any suggestions?

Sdickie
  • 5
  • 3
  • Possible duplicate of [What is a NullPointerException, and how do I fix it?](https://stackoverflow.com/questions/218384/what-is-a-nullpointerexception-and-how-do-i-fix-it) – Sanket Makani May 25 '17 at 07:32
  • Note that with the `c` constructor you are creating an _array of array of `CheckersBoard` objects_, which is probably not what you want – rrobby86 May 25 '17 at 07:35
  • 1- Nullpointer :the c is seems to be null at positions [0][0], [0][1] ..etc. 2- the code is doesn't look right as you only initialising array of 8 but you want to iterate 12 times so you get ArrayIndexOutOfBoundsException if you fix the null pointer. – justMe May 25 '17 at 07:48

2 Answers2

0

I see two major problems in your code:

  1. You're iterating over 0-8 elements for x and 0-12 for y, but in declaration you has 0-7 for x and the same for y
  2. NullPointerException. This caused because array declaration will fill your array with null values, so you're comparing null with Color.Blue which is incorrect.

With the both fixes code will look like this

public int getCheckersBlue()
{
    int counter = 0;
    for(int x = 0; x < 8; x++)
    {
        for(int y = 0; y < 8; y++)
        {
            if(Color.BLUE.equals(c[x][y]))
            {
                counter++;
            }
        }
    }
    return counter;
}

But I think it's still logically incorrect.

Sergey Prokofiev
  • 1,815
  • 1
  • 12
  • 21
0

Okay, a few of things...

  1. You are iterating through 12 every time in the inner loop when it should be 8.

  2. Color.Blue is a JavaFX Paint, I believe. This is not really what you should be using. Unless you have made your own Enumeration type of Color, you should do so. Here is a link for how to do so with relevant examples.

  3. You are checking equality of two different types: CheckersBoard and Color. You should have a CheckersBoard.getSpace(x, y).getColor() or CheckersBoard.getSpace(x, y).getOccupancy() (which should have a NoOccupancy option) if we want to be completely logistically sound with our naming.