2016-12-09 6 views
0

これらのメソッドは配列のサイズを要求する必要があります(エラーなし)。配列内のすべての要素はfalse(エラーなし)になり、最後に配列を出力する必要があります... しかし、私は29行目(コードにマークされています)の例外を受け取ります。ブール配列printBoard()内のnullPointerException

私は自分のコードで何が間違っているのか分かりません。 initBoard

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(); 
} 
+3

あなたがその行で参照解除するのは 'board'だけなので、' board'は 'null'でなければなりません。 [NullPointerExceptionとは何ですか?どうすれば修正できますか?](http://stackoverflow.com/questions/218384/what-is-a-nullpointerexception-and-how-do-i-fix-it ) –

+0

'boolean [] [] board = new boolean [nrRows] [nrColumns];'ローカル変数を作成するので、 'printBoard()'のようにatributteクラスで作業していない 'initBoard()'で –

+0

人あなたの質問に答えましたが、もう少しお手伝いするために、あなたはNULLチェックを行わずにboard [0]を使うべきではありません。ほとんどの場合、NULLチェックは本当に良いことです。ボード[0]を使用する前に 'if(board!= null)'を実行してください –

答えて

0
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; 
} 

ありがとう...私はそれを見ませんでした。今度は、アレイボードを初期化します。

1

新しいボードを初期化していないグローバルボードとメソッドが返すときのでboardはまだ初期化されていないですしています。

関連する問題