2

根据我的编译器,我得到了一个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";
}

}
4

3 回答 3

1

您试图在chart初始化之前填充数组(并且 is null)。数组初始化应该在这个语句之前的某个地方:

chart[rowcount][columncount] = seat;

初始化的一个可能位置是SeatChart构造函数的开头。在那里,您可以使用input数组的大小来设置大小chart

SeatChart(double input[][]) {
    chart = new Seat[input.length][input[0].length];
    // ...
}

值得一提的是,它input[0].length给出了第一行的长度,即矩形数组中的数。

于 2013-11-13T12:40:07.773 回答
0

您需要this.chart为每个this.chart[i].

于 2013-11-13T12:40:40.397 回答
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. 
 }
于 2013-11-13T12:41:09.217 回答