![](/img/trans.png)
[英]NullPointerException while passing 2d array to the constructor
[英]passing a 2d array to a constructor
所以我有一個在測試器類中創建的二維數組,然后我試圖發送它並在構造函數中創建一個副本,但是得到一個空錯誤。 我哪里出錯了? 構造函數:
public TheaterSeatSeller(int[][] newSeats)
{
for(int i=0; i<newSeats.length; i++)
{
for(int j=0; j<newSeats[i].length; j++)
{
seats[i][j]=newSeats[i][j];
}
}
}
然后是測試員類
public static void main(String[] args){
//initialize the available seats
int[][] emptySeats = {
{10,10,10,10,10,10,10,10,10,10},
{10,10,10,10,10,10,10,10,10,10},
{10,10,10,10,10,10,10,10,10,10},
{10,10,20,20,20,20,20,20,10,10},
{10,10,20,20,20,20,20,20,10,10},
{10,10,20,20,20,20,20,20,10,10},
{20,20,30,30,40,40,30,30,20,20},
{20,30,30,40,50,50,40,30,30,20},
{30,40,50,50,50,50,50,50,40,30}};
TheaterSeatSeller mySeats = new TheaterSeatSeller(emptySeats);
}
您必須在分配值之前初始化座位數組。 這應該解決它。
public TheaterSeatSeller(int[][] newSeats) {
seats = new int[newSeats.length][newSeats[0].length];
for (int i = 0; i < newSeats.length; i++) {
for (int j = 0; j < newSeats[i].length; j++) {
seats[i][j] = newSeats[i][j];
System.out.println(seats[i][j]);
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.