2015-07-21 64 views
-2

为什么我会得到NullPointerException?我实例化了Board.setStartPosition中的节点对象。然后我使用b.getStartPosition()从我的驱动程序中调用它。我简化了代码,只留下相关信息。奇怪的Java空指针异常

Driver.java

Static Board b; 

public static void main(String[] args){ 
    b = new Board(3,3); 
    b.setStartPosition(1, 1); 
    b.createPath(b.getStartPosition()); 
} 

Board.java

public class Board { 
    private int length; 
    private int width; 
    private Node[][] board; 
    private ArrayList<Node> openList; 
    private ArrayList<Node> closedList; 
    private Node startPosition; 
    private Node endPosition; 

    Board(int length, int width){ 
     board = new Node[length][width]; 

     Random rand = new Random(); 

     for(int row=0; row < board.length; row++){ 
      for(int col=0; col < board[row].length; col++){ 

       int randomNum = rand.nextInt(10); 

       if(randomNum == 0){ 
        board[row][col] = new Node('X',row,col); 
       } 
       else{ 
        board[row][col] = new Node('O',row,col); 
       } 
      } 
     } 
    } 

    public Node getStartPosition() { 
     return this.startPosition; 
    } 

    public void setStartPosition(int x, int y) { 
     board[x][y].setStatus('S'); 
     board[x][y].setParent(null); 
     startPosition = new Node('S', x, y); 
     startPosition.setG(0); 
    } 

    public void createPath(Node n){ 

     //Continue until we cant find a path or we exhaust our searches 

     //THIS IS WHERE I GET A NULLPOINTER. IT SEEMS TO THINK THAT MY NODE 
     //n is null, eventhough when i pass it, i pass it by getting the startposition node 
     //Add startPosition to closed list 
     closedList.add(n); 

     //Add things around start square to openList if applicable 
     addToOpenList(n);  
    } 

} 
+3

你的堆栈跟踪在哪里?我的猜测是你的'closedList'没有初始化 – user2718281

+1

你在哪里初始化'closedList'? –

回答

1

您从未初始化closedListopenList。更改

private ArrayList<Node> openList; 
private ArrayList<Node> closedList; 

喜欢的东西

private ArrayList<Node> openList = new ArrayList<>(); 
private ArrayList<Node> closedList = new ArrayList<>(); 

更好,但我建议你编程的List接口。所以真的是这样的,

private List<Node> openList = new ArrayList<>(); 
private List<Node> closedList = new ArrayList<>(); 
1

您还没有实例化您的openList & closedList。你刚才宣布他们:

private ArrayList<Node> openList; 
private ArrayList<Node> closedList; 

因此,当你这样做

 closedList.add(n); 

     //Add things around start square to openList if applicable 
     addToOpenList(n); 

你会得到NullPointerException

您可以初始化你的清单这里在声明中提到:

private ArrayList<Node> openList = new ArrayList<>(); 
private ArrayList<Node> closedList = new ArrayList<>(); 
+0

谢谢。我应该知道这一点...我正在调试30分钟,但无法弄清楚。我认为它必须是一件容易的事 – grauddi

1

你似乎从来没有设置closedList。你为什么期望它不是null