0

So, I got a 2D array (I initalised it at the beginning, because it was in use in two different methods - is there a better way of doing this?), but now when my method, initalise() runs, it's supposed to change the values of the array, but it doesn't, as my second method, toString(), and in my debugger both say that the 2D array variable seatArray is null, after the initalise() method finishes.

public class SeatLayout 
{
    int numberOfRows = 0;
    int numberOfColumns = 0;
    Seat[][] seatArray = new Seat[10][7];

    private void initialise()
    {   
        Seat[][] seatArray = new Seat[numberOfRows][numberOfColumns];
        
        for(int i = 0; i < this.numberOfRows;++i)
        {
            for(int j = 0; j <this.numberOfColumns;++j)
            {
                if(i <=4)
                {
                    if(j == 0 || j == this.numberOfColumns)
                    {
                        seatArray[i][j] = new Seat(SeatType.WINDOW, new Position(new Row(numberOfRows), new Column((char)(numberOfColumns+48))));
                        seatArray[i][j].setFirstClass(true);
                    }

public String toString()
    {

    for (int i = 0; i < this.numberOfRows;++i)
        {
            for (int j = 0; j < this.numberOfColumns;++j)
                    {
                        System.out.print(this.seatArray[i][j].toString());

I tried to include only the necessary code.

Exccc
  • 11
  • 1
  • You're shadowing the `seatArray` variable by re-declaring it in the initialize method, and thus are initializing the temporary local variable inside the method, one that disappears as soon as the initialize method ends, and you're leaving the class field untouched. Solution: Don't re-declare the variable, but rather use the field that has already been declared. – Hovercraft Full Of Eels Aug 22 '21 at 12:21
  • In other words, in the initialize method, change `Seat[][] seatArray = new Seat[numberOfRows][numberOfColumns];` to `seatArray = new Seat[numberOfRows][numberOfColumns];` Note the difference? – Hovercraft Full Of Eels Aug 22 '21 at 12:22
  • @HovercraftFullOfEels yup, I knew what the issue was, and that that was the issue, but i was just a bit confused in this part of the program. I did the change and damn you just solved like 2 hours of my frustration, but fuck, thanks mate. – Exccc Aug 22 '21 at 12:26

0 Answers0