广度优先搜索java.lang.NullPointerException

时间:2017-02-20 13:15:47

标签: java breadth-first-search

我正在编写一个拼图程序。当我编译我的Java程序时,它成功了。但是当我运行它时,它会显示

Solution to problem using breadth first :
Exception in thread "main" java.lang.NullPointerException 
at SolvingProblem.isGoal(SolvingProblem.java:24)
at AbstractTreeSearch.solve(AbstractTreeSearch.java:31)
at EightP.main(EightP.java:15)

我花了几个小时来修复代码但不成功。理想情况下,它应该显示3x3阵列配置。谁能在这里帮助我并指出问题是什么?

State initialState = new State(State.arrayA);
State GoalState = new State(State.arrayG);

@Override
public Object getInitialState() {
    return initialState;
}

@Override
public boolean isGoal(Object state) {
    return state.equals(GoalState);
}

下面的另一个课程

  public Node solve(Problem problem) {

    //initialize the search tree using the initial state of problem
    frontier = initFrontier();
    frontier.addAll(expand(new Node(problem.getInitialState()), problem));
    //Starting frontier
    boolean done = false;
    Node solution = null;
    while (!done) {
        if (frontier.isEmpty()) {
            System.out.println("Blank frontier");
            done = true;
        } else {
            Node node = chooseLeafNode(frontier, problem);
            //inspecting node
            if (problem.isGoal(node.getState())) {
                System.out.println("Solution found");
                System.out.println();
                solution = node;
                done = true;
            } else {
                //Expanding node, frontier is..
                frontier.addAll(expand(node, problem));

            }
        }
    }

1 个答案:

答案 0 :(得分:0)

从可用的代码中,似乎很可能原因是这一行:

problem.isGoal(node.getState())

node.getState()的代码正在返回null,然后又传递给isGoal方法,然后该方法会尝试调用state.equals(GoalState)。由于state为空且不是对象,因此您无法调用equals,因此NullPointerException(NPE)。

确保getState()不返回null(如果不允许),或者如果getState()可以为null,则需要isGoal方法检查/处理此方法,例如:

@Override
public boolean isGoal(Object state) {
    return state != null && state.equals(GoalState);
}

在这个例子中,我避免使用NPE,因为&&是一个短路操作符,这意味着除非必要(避免NPE),否则不会评估右侧。有关详细说明,请参阅here