0

I'm running tests for my board class in a game I am making, and continue getting a nullpointerexception when I try to search for an object in my array.

public class Board extends java.util.Observable{

//10x10 array that holds the tokens
private Token board[][];

/**
 * Constructs board 
 */
public Board(){
    board = new Token[10][10];
}

/**
 * Adds token to the board at the location that the token is
 * @param token     token to be added
 */
public void addToken(Token token){
    Location loc = token.getLocation();
    board[loc.getX()][loc.getY()] = token;

    //notifies view that it needs to redraw the board
    notifyObservers();
}

/**
 * move token that is already on the board
 */
public void moveToken(Token token){
    //checks if the piece is in the board
    boolean moved = false;

    //finds piece
    for(int i = 0; i < board.length; i++){
        for(int j = 0; j<board[i].length; j++){
            if(board[i][j].equals(token)){  //THIS IS THE LINE THAT CAUSES THE ERROR
                board[i][j] = null;
                moved = true;
            }
        }
    }
    //if piece is not on board, throw error
    if(!moved) throw new GameError("Attempted to move token that is not on the Board");

    //add the token in its new location
    addToken(token);
}

The exception is caused in the moveToken method, which I call in the following test.

    @Test 
public void testAddToken(){
    Board b = new Board();
    Token[][] board = b.getBoard();
    Token t = new Token('a', "a....", true);
    t.setLocation(new Location(4,4));
    b.addToken(t);
    board = b.getBoard();
    assertEquals(board[4][4],t);
    t.setLocation(new Location(2,1));
    b.moveToken(t); //THIS IS WHEN THE ERROR IS CAUSED
    assertEquals(board[2][1],t);
}

I added some System.out.print tests to check when exactly the error is caused, and it happens on the very first loop, when both i & j are zero.

Thank you in advance for any help!

0 Answers0