anna anna - 4 months ago 10
Java Question

Java: arrays, multiple classes

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?

Answer

Once a parking is done you need to break, see below code

public void parkCar(Car car) {
    for (int i = 0; i < cars.length; i++) {
        if (cars[i] == null) {
            cars[i] = car;
            break; // do not allocate other null spaces with same car, leave space for the next cars
        }
    }
}

Edit as suggested by Mshnik simply you can return instead of break. Post loop can be used to handle the exceptional flow, i.e. incase there is not vacant space left for parking.

public void parkCar(Car car) {
    for (int i = 0; i < cars.length; i++) {
        if (cars[i] == null) {
            cars[i] = car;
            return; // do not allocate other null spaces with same car, leave space for the next cars
        }
    }

   System.out.println("Sorry, no space left for parking");
  //here you can add code so as to see a parking space at some other place , may be you can have a 2-d array with each row representing a parking space. 
}
Comments