Below is part of the solution to an homework assignment I had, and I don’t know why he has two for loops. If it was me, I would have set if (carsParked[i] == c) then set carsParked[i]=null
I don’t understand why second for loop statement can anyone explain?
By the way, CarsParked array is a type of Car class which stores car objects that are parked.
public void driveOut(Car c)
{
for (int i=0; i<carsParked.length; i++) // Loop through the carParked array
{
if(carsParked[i] == c) // Find Car c at index i
{
//carsParked, remove(c);
for (int j=i; j<carsIn-1; j++)
{
carsParked[j] = carsParked[j+1];
}
carsParked[carsIn-1] = null;
carsIn = carsIn - 1;
}
}
}
This is how cars are parked
public void driveIn(Car c)
{
if(carsIn < carsParked.length)
{
carsParked[carsIn] = c;
carsIn = carsIn + 1;
}
else // error message
{
System.out.println("Park " + location + " is full, for " + c);
}
}
Say you have an array with 5 cars:
[Car1, Car2, Car3, Car4, Car5], and you call the methoddriveOut(Car3).By setting the value to null when you find it, you end up with
[Car1, Car2, null, Car4, Car5]. This practice can lead toNullPointerExceptiontype errors, becausenullvalues are in the middle of the array, and the data is not compacted.The solution is basically eliminating the gap by starting from that point and shifting the remaining cars to the left:
Then outside the loop, the last entry is set to null, leaving you with
[Car1, Car2, Car4, Car5, null]