I have 3 classes- Car, ParkingLot and Driver. In the ParkingLot class, I have a method called parkCar which is supposed to check for the first empty spot and place the car object there:
public void parkCar(Car car) {
for (int i = 0; i < cars.length; i++) {
if (cars[i] == null) {
cars[i] = car;
}
}
}
In the Driver class, there is supposed to be a method which calls the parkCar method to put a car object in a parking spot (driver should no longer have the car):
public void putCarInParkingSpot(Parkinglot parkingLot) {
parkingLot.parkCar(this.car);
this.car = null;
}
Finally, I have a showParkingLot method in the ParkingLot class which is supposed to show all cars in the array:
public void showParkingLot() {
for (int i = 0; i < cars.length; i++) {
if (cars[i] != null) {
System.out.println(cars[i].getModel());
}
}
}
When I use showParkingLot, the 1 car object gets placed in every spot in the array (prints it out 15 times), not just the first null spot(cars[0]). Can anyone explain why?