0

i was coding a puzzle program. When i compiled my Java program, it was successful. But when i run it, it shows

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)

I spent several hours and fixing the code but unsuccessful. Ideally, it is supposed to show 3x3 array configuration. Could anyone help me here and point out what is the problem?

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

Another class below

  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 Answers1

0

From the code available, it seems highly likely that the cause is this line:

problem.isGoal(node.getState())

The code for node.getState() is returning null and this is in turn passed on to isGoal method which then attempts to call state.equals(GoalState). Since state is null and not an object, you can't call equals, hence the NullPointerException (NPE).

Either ensure getState() doesn't return null (if it's not allowed to), or if getState() can be null, you need to have isGoal method check/handle this e.g.:

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

In this example I avoid NPE since && is a short-circuit operator, which means the right hand side isn't evaluated unless it's necessary (avoiding the NPE). See here for further explanation.

Community
  • 1
  • 1
xlm
  • 6,854
  • 14
  • 53
  • 55
  • Hi xim, thank you. This is useful advice. I troubleshoot it and found out that my chooseleafnode() didn't return any value. Thus null. Then it lead to my variable initialization in another class. It has something to do with 2D array unable to pass value into chooseleafnode(). I changed back to 1D array and it works. – lowerbound Feb 21 '17 at 12:18