以下是我的家庭作业解决方案的一部分,我不知道为什么他有两个 for 循环。如果是我,我会设置 if (carsParked[i] == c) 然后设置 carsParked[i]=null 我不明白为什么第二个 for 循环语句谁能解释?
顺便说一句,CarsParked 数组是一种 Car 类,它存储停放的汽车对象。
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;
}
}
}
汽车是这样停放的
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);
}
}