尝试填充数组时出现java.lang.NullPointerException错误

use*_*907 1 java arrays nullpointerexception

我试图将二维数组price [] []中的值(整数)放入数组seatArray [] []中对象的cost变量中.我认为问题在于我试图将价格数组中的值放入空中,因为seatArray数组只包含对null的对象引用.我该如何解决这个问题?

调用构造函数的行:

        SeatChart seatArray = new SeatChart(givenArray);
Run Code Online (Sandbox Code Playgroud)

构造方法:

public SeatChart(int[][] prices)
{
    Seat[][] seatArray = new Seat[9][10];
    for(int i = 0; i < 9; i++)
    {   
        for(int j = 0; j < 10; j++)
        {
            seatArray[i][j].cost=prices[i][j];
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

Sud*_*hul 6

Seat[][] seatArray = new Seat[9][10];
Run Code Online (Sandbox Code Playgroud)

这只是声明了数组,并没有用Seat对象初始化数组元素.

for(int i = 0; i < 9; i++)
{   
    for(int j = 0; j < 10; j++)
    {
        // I've used a default Seat() constructor to create the object, in your actual case, it may differ.
        seatArray[i][j] = new Seat(); // Initializing each array element with a new Seat object
        seatArray[i][j].cost=prices[i][j];
    }
}
Run Code Online (Sandbox Code Playgroud)