简体   繁体   中英

NullPointerException when populating a 2D array

According to my compiler I am getting a NullPointerException on chart[rowcount][columncount] = seat; but I have initialized the seat variable in the line before. I am trying to create a multivariable array of seats and populate it with the seats using the for loops. I had just asked a question about this and thought I understood how to avoid these but I guess not. How am I can I fix this 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";
}

}

You're trying to fill the array chart before it is initialized (and is null ). Array initialization should come somewhere before this statement:

chart[rowcount][columncount] = seat;

One possible location for initialization is beginning of the SeatChart constructor. There you can use size of the input array to set size of chart :

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

It is worth mentioning is that input[0].length gives the length of first row which is number of columns in a rectangular array.

您需要为this.chart和每个this.chart[i]分配内存。

You can't set value on following declaration.

private Seat chart[][];

You need to initialize Seat as:

private Seat chart[][];

 SeatChart(double input[][]) {
    chart[][]=new Seat[input[0].length][input[1].length];
          //this initialization is needed to avoid NPE. 
 }

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