2013-12-16 41 views
0

我創建一個迷宮發電機作爲一個有趣的側面項目,我遇到了在那裏我的代碼以某種方式返回null,我不知道爲什麼

newTile.getxCoord() 

是創建一個空指針異常的問題,我不知道爲什麼。我進行了檢查,以確保我的「瓷磚」的創建使用了存在於我的電路板範圍內的正面價值觀。

這裏是整個方法和代碼的鏈接https://github.com/Dibes/Maze/blob/master/src/MazeCreation/DepthFirst.java#L30

對於通過我的思維過程的快速步行此代碼

// Set the starting tile as visited and current 
    TileGenerator.setTileVisible(Maze.startingTile.getxCoord(), Maze.startingTile.getyCoord(), 0); 
// Set the starting tile as the current tile 
    TileGenerator.setTileCurrent(Maze.startingTile.getxCoord(), Maze.startingTile.getyCoord(), 1); 
    // Set the last tile as the starting tile 
    Tile lastTile = Maze.startingTile; 
    // Grab a new tile that is within the bounds of the map and is greater than 0 
    Tile newTile = TileGenerator.getTile(Utility.getHorizNext(lastTile.getxCoord(), -1, 1), Utility.getVertNext(lastTile.getyCoord(), -1, 1)); 
    while(!TileGenerator.isTilesVisited()) { 
     // Debug testing 
     if (newTile.getxCoord() < 0 || newTile.getyCoord() < 0) { 
      System.out.println(newTile.getxCoord() + " " + newTile.getyCoord()); 
     } 
     // Set the current tile visible 
     TileGenerator.setTileVisible(newTile.getxCoord(), newTile.getyCoord(), 0); 
     // Set the last tile marked as not current 
     TileGenerator.setTileCurrent(lastTile.getxCoord(), lastTile.getyCoord(), 0); 
     // Set the newly found tile marked as current (shows up as red on the board) 
     TileGenerator.setTileCurrent(newTile.getxCoord(), newTile.getyCoord(), 1); 
     // Grab new tile 
     lastTile = newTile; 
     newTile = TileGenerator.getTile(Utility.getHorizNext(lastTile.getxCoord(), -1, 1), Utility.getVertNext(lastTile.getyCoord(), -1, 1)); 
     // A sleep in the thread so i could see the generation slowly 
     try { 
      Thread.sleep(200); 
     } catch (InterruptedException e) { 
      e.printStackTrace(); 
     } 
    } 

對不起,是短暫的,我只是我不知道爲什麼它會創建一個空指針。

+0

請發佈相關的代碼,而不是發佈鏈接。 – rgettman

+1

'newTile'爲null,或'getxCoord()'下的內容爲空。看看你的堆棧跟蹤來確定哪個。 – pamphlet

+0

你不檢查'getTile'是否返回NULL。你確定它不能失敗? – usr2564301

回答

2

newTileTileGenerator.getTile()創建 - 按照來源TileGenerator,這種方法可以返回一個空實例:

https://github.com/Dibes/Maze/blob/master/src/Components/TileGenerator.java#L78

public static Tile getTile(int xCoord, int yCoord) { 
    for (int[] tile : mapTiles) { 
     if (tile[Tile.XCOORD] == xCoord && tile[Tile.YCOORD] == yCoord) { 
      return new Tile(tile[Tile.XCOORD], tile[Tile.YCOORD], tile[Tile.XLOC], tile[Tile.YLOC], tile[Tile.ISFILLED], tile[Tile.ISVISITED], tile[Tile.ISCURRENT]); 
     } 
    } 
    return null; 
} 

您的代碼產生NullPointerException因爲瓷磚是空 - 有你寫了一個單元測試,涵蓋你正在使用的案例?

+0

這正是問題所在!謝謝!我將盡快將其設置爲答案 – Dibesjr

+1

更重要的是發現錯誤的方式是確保將來不會再發生一次單元測試。您可能還想重新訪問'TileGenerator'中的'getTile'方法。將'null'作爲後備值返回有意義嗎?這裏的例外會更有意義嗎? – matt

+0

我認爲null在這種情況下很有意義,因爲它無法在該點上達到平鋪,所以平鋪無效。如果我拋出異常,它會中斷程序的流向,我寧願繼續並修正座標,而不是完全停止它。但是我同意,當談到其他計劃時,我應該更多地考慮這個問題! – Dibesjr

相關問題