简体   繁体   English

将二维数组传递给构造函数

[英]passing a 2d array to a constructor

So i have a 2d array that i create in a tester class and then i am attempting to send it and create a duplicate in the constructor, but a get a null error.所以我有一个在测试器类中创建的二维数组,然后我试图发送它并在构造函数中创建一个副本,但是得到一个空错误。 Where am i going wrong?我哪里出错了? The 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];
   }
  }

}

and then the tester class然后是测试员类

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

You have to initialize the seats array before assigning the value.您必须在分配值之前初始化座位数组。 This should fix it.这应该解决它。

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM