宽度优先搜索java.lang.NullPointerException
我正在编写一个益智程序。当我编译Java程序时,它是成功的。但当我运行它时,它显示宽度优先搜索java.lang.NullPointerException,java,breadth-first-search,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
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));
}
}
}
从可用的代码来看,原因很可能是这一行:
problem.isGoal(node.getState())
node.getState()
的代码返回null
,这又传递给isGoal
方法,然后该方法尝试调用state.equals(GoalState)
。由于状态
为空且不是对象,因此不能调用equals
,因此出现NullPointerException
(NPE)
确保getState()
不返回null(如果不允许),或者如果getState()
可以为null,则需要使用isGoal
方法检查/处理此问题,例如:
@Override
public boolean isGoal(Object state) {
return state != null && state.equals(GoalState);
}
在本例中,我避免使用NPE,因为
&&
是一个短路运算符,这意味着除非必要,否则不会对右侧进行评估(避免使用NPE)。有关详细说明,请参阅。嗨,xim,谢谢。这是有用的建议。我对它进行了故障排除,发现我的chooseleafnode()没有返回任何值。因此无效。然后它导致我在另一个类中初始化变量。这与2D数组无法将值传递到chooseleafnode()有关。我改回了1D阵列,它可以正常工作。