【问题标题】:boolean array java.lang.NullPointerException in printBoard() [duplicate]printBoard() 中的布尔数组 java.lang.NullPointerException [重复]
【发布时间】: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


【解决方案1】:

initBoard 中,您正在初始化一个新板而不是全局板,因此当方法返回时,board 仍未初始化。

【讨论】:

    【解决方案2】:
    private void initBoard(){
        boolean[][] array = new boolean[nrRows][nrColumns]; 
        for(int i = 0; i < nrRows; i++){
            for(int y = 0; y < nrColumns; y++){
                array[i][y] = false;
            }
        } board = array;
    }
    

    谢谢...我没看到。现在我初始化阵列板。

    【讨论】:

      猜你喜欢
      • 2013-10-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-02-20
      • 1970-01-01
      • 2018-12-26
      • 2014-06-11
      • 1970-01-01
      相关资源
      最近更新 更多