2017-02-20 2 views
0

나는 퍼즐 프로그램을 코딩하고 있었다. Java 프로그램을 컴파일 할 때 성공했습니다. 하지만 내가 그것을 실행하면, 그것은 보여줍니다너비 우선 검색 java.lang.NullPointerException

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

      } 
     } 
    } 

답변

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

를 I &&은 단락 회로 연산자이므로 NPE는 필요하지 않으면 평가되지 않습니다 (NPE는 피함). 자세한 설명은 here을 참조하십시오.

+0

안녕하세요, 감사합니다. 이것은 유용한 조언입니다. 나는 문제를 해결하고 내 chooseleafnode()가 어떤 값도 반환하지 않는다는 것을 알아 냈다. 따라서 null. 그런 다음 다른 클래스에서 변수 초기화로 연결됩니다. 그것은 2D 배열이 chooseleafnode()에 값을 전달할 수없는 것과 관련이 있습니다. 다시 1D 배열로 바뀌었고 작동합니다. – lowerbound