填充2D数组时出现NullPointerException

时间:2013-11-13 12:38:29

标签: java multidimensional-array nullpointerexception

根据我的编译器,我在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";
}

}

3 个答案:

答案 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. 
 }