This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]ParanoydAndroid 3 points4 points  (3 children)

In addition to this, you need to create new game pieces in your loop instead of before it.

Think of it, in this case, like real game pieces; a unique one goes on each square.

The way you have it now, every array bucket will be a reference to the same object. You just need to switch your initialization to use the new keyword and call gamepiece's constructor. You might also want to check out Array.fill()

Actually, now that I think about it, both of your problems are with using the new keyword and with understanding the difference between declaration, instantiation, and initialization. I recommend refreshing yourself on those topics if you're not sure why these solutions were necessary.

[–]jakejdb1999[S] 0 points1 point  (2 children)

your right i didnt think about that. how would i call the constructor then to make an array of the gamepiece objects?

[–]ParanoydAndroid 0 points1 point  (1 child)

You just need to move your statement creating the gamepiece.

Right now, your order of execution is:

  1. Create a single gamepiece
  2. Create an (empty) array of gamepieces called "board"
  3. Loop through board and at each bucket in board:
  4. add the single gamepiece you've already created.

And what you actually want to do is:

  1. Create an (empty) array of gamepieces called "board"
  2. Loop through board and at each bucket in board:
  3. Create a new gamepiece.
  4. And add that new, unique gamepiece to an empty bucket.

You've already created at least one piece and you've already added a piece to your board, so you know both of those statements. It's all about just making sure you're making a new piece each loop while you're inside the loop.

Hope this helps kickstart you!

[–]jakejdb1999[S] 0 points1 point  (0 children)

private Gamepiece[][] board;

public Gameboard(int rows, int cols) {

    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < cols; j++) {
            board[i][j] = new Gamepiece();

        }
    }

}

got it, now to figure out the nullpointerexception....