检查可能为空的对象时避免NullPointerException(Java)

时间:2017-09-15 07:23:50

标签: java

public boolean hasCapturableEnemy(Piece[][] board, int startX, int startY) {

    //If the Pawn belong to the Upper Team (Faces downward)
    if(board[startX][startY].getTeam() == Player.UP) {

        //If a Piece exists diagonally in front of it on an adjacent tile, return true
        if((board[startX - 1][startY + 1].getTeam() != Player.UP) || (board[startX - 1][startY - 1].getTeam() != Player.UP)) {
            return true;
        } else {
            return false;
        }

    } else { //If the Pawn belongs to the Down Team (Faces upward)

        //If a Piece exists diagonally in front of it on an adjacent tile, return true
        if((board[startX + 1][startY + 1].getTeam() != Player.DOWN) || (board[startX + 1][startY - 1].getTeam() != Player.DOWN)) {
            return true;
        } else {
            return false;
        }
    }
}

我构建了一个布尔函数,试图检查Pawn国际象棋棋子是否有敌人要捕获。在检查Pawn对角线上的棋子是否是敌人的情况下,我得到一个NullPointerException,因为我正在检查两个对角线位置,其中一个可能是一个空位置(null)。

(board[startX + 1][startY + 1].getTeam() != Player.DOWN) 
//This could be NULL

如何在检查位置和检查其成员变量(Team)时避免获取NullPointerException?

0 个答案:

没有答案