简体   繁体   中英

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

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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