根据我的编译器,我在NullPointerException
上获得chart[rowcount][columncount] = seat;
但我已经在之前的行中初始化了座位变量。我正在尝试创建一个多变量的座椅阵列,并使用for循环填充座椅。我刚刚问了一个关于这个的问题,并且认为我理解如何避免这些,但我想不是。我怎么能修复这个nullPointerException?
public class SeatChart {
private Seat chart[][];
SeatChart(double input[][]) {
Seat seat;
for (int rowcount = 0; rowcount < input[0].length; rowcount++) {
for (int columncount = 0; columncount < input[1].length; columncount++) {
seat = new Seat(input[rowcount][columncount]);
chart[rowcount][columncount] = seat;
}
}
}
public String buySeat(int row, int column) {
try {
chart[row][column].markSold();
return "Seat [" + row + "]" + "[" + column + "] was purchased.";
} catch (ArrayIndexOutOfBoundsException e) {
return "The seat your tried to purchase does not exist.";
}
}
public String buySeat(double price) {
int k = 0;
for (int rowcount = 0; rowcount < chart[0].length; rowcount++) {
for (int columncount = 0; columncount < chart[1].length; columncount++) {
if (k == 0) {
if (chart[rowcount][columncount].getPrice() == price) {
chart[rowcount][columncount].markSold();
return "Seat [" + rowcount + "]" + "[" + columncount + "] was purchased.";
}
}
}
}
return "There was an error, please try again";
}
}
答案 0 :(得分:1)
您正在尝试在数组初始化之前填充数组chart
(并且是null
)。数组初始化应该在此语句之前的某处:
chart[rowcount][columncount] = seat;
初始化的一个可能位置是SeatChart
构造函数的开头。在那里,您可以使用input
数组的大小来设置chart
的大小:
SeatChart(double input[][]) {
chart = new Seat[input.length][input[0].length];
// ...
}
值得一提的是,input[0].length
给出了第一行的长度,它是矩形数组中列的数量。
答案 1 :(得分:0)
您需要为this.chart
和每this.chart[i]
分配内存。
答案 2 :(得分:0)
您无法在以下声明中设置值。
private Seat chart[][];
您需要将Seat
初始化为:
private Seat chart[][];
SeatChart(double input[][]) {
chart[][]=new Seat[input[0].length][input[1].length];
//this initialization is needed to avoid NPE.
}