猿问

在 Java 中搜索二维数组的 For 循环返回 NullPointerException

对于大学的一个项目,我必须创建一个井字游戏。


我有这个for带有if语句的循环来搜索 3x3 大小的二维数组,如果它是X或O(枚举),则返回。这导致显示哪一方赢得了比赛。


但是,我遇到的问题是,如果 2D 数组不完整,就像所有 9 个框都没有填充X或 一样O,该方法会显示NullPointerException.


编辑:我必须补充一点,我要求空网格与null其他单元测试假设grid[][]初始化为null.


错误:


Exception in thread "main" java.lang.NullPointerException

at TicTacToeImplementation.whoHasWon(TicTacToeImplementation.java:80)

at ApplicationRunner.main(ApplicationRunner.java:24)

代码:


public enum Symbol {

    X, O

}


private Symbol winner;


public Symbol whoHasWon() {


    for (Symbol xORo : Symbol.values()) {


        if ((grid[0][0].equals(xORo) &&

                grid[0][1].equals(xORo) &&

                grid[0][2].equals(xORo))) {

            winner = xORo;

            isGameOver = true;


            break;

        } else if ((grid[1][0].equals(xORo) &&

                grid[1][1].equals(xORo) &&

                grid[1][2].equals(xORo))) {

            winner = xORo;

            isGameOver = true;


            break;}

           else if { //Code carries on to account for all 8 different ways of winning


        } else {


            isGameOver = true;

        }

    }


    return winner;

}


慕后森
浏览 227回答 3
3回答

森林海

正如指出这个帖子,你可以使用equals()或==比较枚举,但使用==是null安全的,而equals()不是。所以基本上,只需像这样写你的支票:if (grid[0][0] == xORo &&    grid[0][1] == xORo &&    // etc.但是,如果您想使用该equals()方法,您可以编写一个方法来检查null然后比较两个值并返回结果:public boolean isEqual(Symbol s1, Symbol s2) {    if (s1 != null && s1.equals(s2)) {        return true;    }    return false;}然后,您可以isEqual()像这样调用该方法:if (isEqual(grid[0][0], xORo) &&    isEqual(grid[0][1], xORo) &&    // etc.
随时随地看视频慕课网APP

相关分类

Java
我要回答