0

Hi I'm creating a 2D array of objects in java and want to access one of the functions that simply returns the boolean value of the variable but for some reason, its throwing an error. The code looks so simple but I can't figure out what I am doing wrong. My guess is something to do with my implementation of the array, but I think I did it right. My goal is to create individual instances of the class for each value in the 100x100 grid.

Here is the code and error I am getting

public class Main {

    public static void main(String[] args) {
        ParkingLot parkingLot = new ParkingLot("Rushi's Parking lot", 100, 100);

        Vehicle car1 = new Car("License");
        parkingLot.registerVehicle();

    }
}

public class ParkingLot {
    String name;
    ParkingSpot[][] parkingGrid;

    public ParkingLot(String name, int xSize, int ySize){
        this.name = name;
        this.parkingGrid = new ParkingSpot[xSize][ySize];
    }

    public void registerVehicle() {
        System.out.println(parkingGrid[0][0].isAvailable());
    }

    public void getNextSpot(Vehicle vehicle){

    }
}

public class ParkingSpot {
    private boolean available = true;
    private String license;
    private int time;

    public boolean isAvailable() {
        return available;
    }

    public void reserveSpot(String license){
        this.license = license;
        this.available = false;
    }
}

Error:

Exception in thread "main" java.lang.NullPointerException
    at ParkingLot.registerVehicle(ParkingLot.java:14)
    at Main.main(Main.java:7)
smac89
  • 39,374
  • 15
  • 132
  • 179
Notorious776
  • 453
  • 6
  • 19

2 Answers2

4

When you create an object of type ParkingLot, the array parkingGrid only contains null-references. You need to actually add the parking spots you want to use.
So far you only specified that parkingGrid has size 100x100 and contains parking spots, but the individual elements aren't there.

Moritz Groß
  • 1,352
  • 12
  • 30
  • 2
    Oh I think I understand. So when I do `this.parkingGrid = new ParkingSpot[xSize][ySize];` its not really creating the object in each element of the array, its only reserving it? – Notorious776 Aug 03 '20 at 21:50
  • 3
    @Notorious776 that's exactly correct. You still need to go to each element and do something like `parkinGrid[x][y] = new ParkingSpot(...)` – smac89 Aug 03 '20 at 21:52
0

Where did you added vehicle? Array is empty, of course it will throw null pointer because there is no any data in it. You need method for adding vehicles and registering positions so you can move to next one when you add vehicle also.