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

0

this.chartforと every の両方にメモリを割り当てる必要があります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 に答える