1

I am trying to put the values (integers) from the 2 dimensional array prices[][] into the cost variable of the objects in the array seatArray[][]. I think the problem is that I am trying to put the values from the prices array into nothing because the seatArray array is only full of object references to null. How would I go about fixing this?

line that calls constructor:

        SeatChart seatArray = new SeatChart(givenArray);

constructor method:

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];
        }
    }
}

2 Answers 2

6
Seat[][] seatArray = new Seat[9][10];

This just declares the array and doesn't initialize the array elements with Seat objects.

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];
    }
}
Sign up to request clarification or add additional context in comments.

7 Comments

That solved the compiling error! But now when I run my program, there is still a nullpointer error. (It happens whenever it has to refer to the objects in the array.) Do you know why this is? (I still don't think the objects are still not being initialized somehow.)
That's what. You need to create a new Seat object and assign it to each element of the array.
It still isn't working. I have that exact code, but I still keep getting a nullpointer exception (but in runtime now). I get the problem when I run code that involves accessing the objects of the array.
I don't see where it would throw an NPE now. Can you post some more code and where exactly is the error being thrown?
I'm having trouble formatting code in the commments. Is there a way to do blocks of code in the comments?
|
0
seatArray[i][j] = new Seat();
seatArray[i][j].cost= prices[i][j];

Or maybe for clarity

Seat seat = new Seat();
seat.setCost(prices[i][j]);
seatArray[i][j] = seat;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.