[英]Java, NullPointerException on using array of Objects
這是代碼示例。 我想創建一個對象的一維數組,為它們提供值,在其他方法中使用它,然后將其打印為二維數組。
起初,我想打印起始板,但是當我嘗試遍歷整個數組時出現NullPointException。 二維數組是6x6矩陣。
public class Field{
int diceCount, playerNumber;
//get and set methods etc.
}
public class Board{
public Field[] board = new Field[36];
public void boardBuilder(){
for(int i = 0; i < board.length; i++){
board[i] = new Field();
//give value to the Fields
}
}
}
public class IoMethods{
public Board board = new Board();
public void boardPrintOut(){
int helper;
for(int i = 0; i < 6; i++){
for(int j = 0; j < 6; j++){
//The next line is where it gets the Exception
helper = board.board[i*6 + j].getPlayerNumber();
//print part
}
}
}
}
您沒有建立董事會。 在遍歷成員之前執行board.boardBuilder()
board.boardBuilder()
for(int i = 0; i < 6; i++){
for(int j = 0; j < 6; j++){
//The next line is where it gets the Exception
helper = board.board[i*6 + j].getPlayerNumber();
//print part
}
}
此行public Field[] board = new Field[36];
創建一個長度為36的數組,其中可以包含Field
對象。 但是現在它的所有36個單元格都為null
。 因此,當您嘗試訪問某些board[i]
您正在訪問null
。
解決方案 :為您的Board
類編寫一個構造函數,並在其中編寫您在boardBuilder()
中編寫的內容,或者直接調用this.boardBuilder()
:
public Board(){
for(int i = 0; i < board.length ; i++)
{
board[i] = new Field();
}
}
原因是未調用boardBuilder()
方法。
現在,您可以先調用board.boardBuilder()
然后再嘗試訪問它,
或者更好地為Board類創建一個構造函數,例如-
Board() {
this.boardBuilder();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.