当尝试返回2D数组时调用getCave方法时,我得到一个NullPointerException。我无法在线找到解决方案。我可以通过用一个不是数组但不符合我需要的新Cave更换返回来让程序无异常地运行。这是我的代码的简化版本:
import java.util.Random;
public class Board {
public static final int DEFAULT_ROWS = 10;
public static final int DEFAULT_COLS = 10;
Cave[][] caveArray = new Cave[DEFAULT_ROWS+2][DEFAULT_COLS+2];
public Board(int rows, int cols){
Random rand = new Random();
for (int j = 1; j < (cols+1); j++) {
for (int i = 1; i < (rows+1); i++) {
Cave temp;
temp = new Cave(i, j);
int rnum = rand.nextInt(100)+1;
if (rnum > 50) {
caveArray[i][j]=temp;
caveArray[i][j].makeBlocked();
}
else if(rnum <=50) {
caveArray[i][j]=temp;
caveArray[i][j].makeOpen();
}
}
}
}
public Cave getCave(int r, int c){
return caveArray[r][c];
}
}
这是来电者:
private void newGame() {
// Set up the game board.
gameBoard = new Board(DEFAULT_ROWS, DEFAULT_COLS);
// Set up the 3 characters.
characters = new ArrayList<Character>();
// Add the adventurer (always in the top left).
characters.add(new Adventurer(gameBoard.getCave(0, 0)));
selected = 0; // Initially select the adventurer.
}
调用:
public class Adventurer扩展了角色{
Adventurer(Cave initLoc) {
super(initLoc);
}
调用:
public abstract class Character implements CaveWorker{
protected Cave location;
public Character(Cave initLoc){
location = initLoc;
location.setOccupied(true);
}
答案 0 :(得分:1)
我可以提供的唯一解释是,如果您尝试索引到caveArray[0][c]
,甚至caveArray[r][0]
,那么我无法观察堆栈跟踪(这些是非常有用的,更多次)什么都可以。
你有两个选择 - 要么使用数组将从索引0开始的事实(它不是那么糟糕),要么抢先将Cave
对象放在第0行和第0列中,而这些对象没有任何实际意义。但是,与(0,0)对齐将是更容易的选择。