迭代二维对象数组时出现NullPointerException

时间:2017-08-06 06:14:06

标签: java arrays

我在我正在制作的游戏中为我的棋盘类运行测试,并且当我尝试在我的阵列中搜索对象时继续获得nullpointerexception。

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);
}

异常是在moveToken方法中引起的,我在下面的测试中调用它。

    @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);
}

我添加了一些System.out.print测试,以检查错误的确切时间,并且它发生在第一个循环上,当时i&amp; j为零。

提前感谢您的帮助!

0 个答案:

没有答案