【发布时间】:2016-12-09 11:25:49
【问题描述】:
这些方法应该询问数组的大小(没有错误),然后数组中的每个元素都应该是假的(没有错误),最后应该打印数组... 但我在第 29 行遇到异常(在代码中标记)
我正在初始化数组,所以我真的不知道我的代码有什么问题。
private boolean[][] board; // true = queen, false = empty
[...]
private void determineBoardSize(){
write("Sprechen sie sich ab wer weiß und wer schwarz ist");
write("weiß muss eine Zahl zwischen 5 und 8 wählen");
nrRows = readInt("Zahl aus {5,6,7,8}");
if(nrRows < 5 || nrRows > 8) determineBoardSize();
write("Schwarz muss nun eine Zahl zwischen ErsteZahl -1 und ErsteZahl + 1 wählen");
nrColumns = readInt("eine Zahl zwischen ErsteZahl -1 und ErsteZahl + 1 wählen");
if(nrColumns < nrRows - 1 || nrColumns > nrRows + 1) determineBoardSize();
private void initBoard(){
boolean[][] board = new boolean[nrRows][nrColumns];
for(int i = 0; i < nrRows; i++){
for(int y = 0; y < nrColumns; y++){
board[i][y] = false;
}
}
}
private void printBoard(){
for (int j = board[0].length - 1; j >= 0; j--) { //java.lang.NullPointerException
System.out.print("\n " + (1 + j));
for (int i = 0; i < board.length; i++) {
System.out.print(board[i][j] ? " X" : " -");
}
}
System.out.print("\n ");
for (int i = 1; i <= board.length; i++) {
System.out.print(" " + i);
}
System.out.println("\n" + (whiteToMove ? white : black) + " ist am Zug.");
}
public void startGame(){
determineBoardSize();
initBoard();
determineFirstPlayer();
printBoard();
mainLoop();
reportWinner();
}
public static void main(String[] args) {
Dame ds = new Dame("Weiß", "Schwarz");
ds.startGame();
}
【问题讨论】:
-
您在该行中取消引用的唯一内容是
board,因此board必须是null。看看What is a NullPointerException, and how do I fix it? -
boolean[][] board = new boolean[nrRows][nrColumns];创建一个局部变量,因此在initBoard()中,您没有像在printBoard()中那样使用类属性 -
这些人回答了你的问题,但只是为了帮助你更多,你不应该在没有 NULL 检查的情况下使用 board[0],大多数时候 NULL 检查确实是一件好事。在使用 board[0] 之前做一个
if(board !=null) -
我会改变的。谢谢!
标签: java arrays nullpointerexception