簡體   English   中英

當我將這個指針推到Deque / ArrayList上時,為什么我得到一個NullPointerException,當它顯然不是Null時

[英]Why am I getting a NullPointerException when I push this pointer onto a Deque/ArrayList when it clearly isn't Null

所以我試着做一個簡單的迷宮求解器(深度優先)。 我不希望幫助解決遞歸方法,但由於某種原因,這會導致NullPointerException在ArrayList的.add單元上進行修復,任何人都可以幫助我知道原因嗎? (MazeExample類為我的老師提供了一個簡單的指向NSEW的迷宮,因此我們可以嘗試測試我們的代碼)。

public static void main(String[] args)
{
    MazeSolver solver = new MazeSolver();
    ExampleMaze example = new ExampleMaze();

    System.out.println(solver.stepsToSolveMaze(example.getStart()));    

}

這是主要的,這里是MazeSolver對象(截至目前它只計算到最后的移動次數,一次一步)。

public class MazeSolver 
{
private int steps=0;
private ArrayList<MazeCell> visitedCells;
private Deque<MazeCell> breadCrumbs;

public int stepsToSolveMaze(MazeCell cell)
{
    visitedCells.add(cell); //this is where the exception is getting thrown.
    breadCrumbs.push(cell);

    if (cell.isFinish())
    {
        return 1;
    }


    if (cell.east() != null && !visitedCells.contains(cell.east()))
    {
        steps += stepsToSolveMaze(cell.east());
    }
    if (cell.south() != null && !visitedCells.contains(cell.south()))
    {
        steps += stepsToSolveMaze(cell.south());
    }
    if (cell.west() != null && !visitedCells.contains(cell.west()))
    {
        steps += stepsToSolveMaze(cell.west());
    }
    if (cell.north() != null && !visitedCells.contains(cell.north()))
    {
        steps += stepsToSolveMaze(cell.north());
    }
    else
    {
        steps--;
        stepsToSolveMaze(breadCrumbs.pop());            
    }

    return steps;

}

在您的示例中,從未設置visitedCells,因此當您嘗試向其添加項時,會導致NullPointerException。 您需要在使用它之前對其進行初始化:

visitedCells = new ArrayList<MazeCell>();

另一方面,breadCrumbs會遇到同樣的問題,所以你可能應該初步確定這個問題:

breadCrumbs = new Deque<MazeCell>();

您沒有初始化數組列表。

在stepsToSolveMaze中添加以下內容

visitedCells = new ArrayList<MazeCell>();

然后添加元素

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM