我正在创建一个迷宫生成器作为一个有趣的副项目,我遇到了一个问题
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 :(得分:2)
newTile
由TileGenerator.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
,因为磁贴为空 - 您是否编写了一个单元测试,其中包含您正在使用的案例?