我试图将二维数组price [] []中的值(整数)放入数组seatArray [] []中对象的cost变量中。我认为问题在于我试图将价格数组中的值放入空中,因为seatArray数组只包含对null的对象引用。我该如何解决这个问题?
调用构造函数的行:
SeatChart seatArray = new SeatChart(givenArray);
构造函数方法:
public SeatChart(int[][] prices)
{
Seat[][] seatArray = new Seat[9][10];
for(int i = 0; i < 9; i++)
{
for(int j = 0; j < 10; j++)
{
seatArray[i][j].cost=prices[i][j];
}
}
}
答案 0 :(得分:6)
Seat[][] seatArray = new Seat[9][10];
这只是声明了数组,并没有用Seat
个对象初始化数组元素。
for(int i = 0; i < 9; i++)
{
for(int j = 0; j < 10; j++)
{
// I've used a default Seat() constructor to create the object, in your actual case, it may differ.
seatArray[i][j] = new Seat(); // Initializing each array element with a new Seat object
seatArray[i][j].cost=prices[i][j];
}
}
答案 1 :(得分:0)
seatArray[i][j] = new Seat();
seatArray[i][j].cost= prices[i][j];
或者为了清楚起见
Seat seat = new Seat();
seat.setCost(prices[i][j]);
seatArray[i][j] = seat;