奇怪的Java Null指针异常

时间:2015-07-21 01:58:15

标签: java nullpointerexception null

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

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 个答案:

答案 0 :(得分:1)

您尚未实例化openList&amp; 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<>();

答案 1 :(得分:1)

您似乎永远不会设置closedList。为什么你不期望null

答案 2 :(得分: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<>();