How do I avoid going below 0 with this for loop ? When this loop executes, it checks if both the vehicle and the garage are in the same space. If not, it decrements the vehicle loop by --i
to get the next available vehicle. when it reaches to index 0
, it is going below index -1
causing the program to crash.
for (int i = vehicles.size() - 1; i >= 0;) {
for (int j = 0; j < garage.size();) {
if (this.garage.get(j).getSpace() == this.vehicles.get(i).getSpace()) {
if (this.garage.get(j).garageRequest(vehicles.get(i).getvehiclesType())
&& this.garage.get(j).getLimit() > 0) {
this.garage.get(j).addvehicles(vehicles.get(i));
this.vehicles.remove(i);
i--;
break;
} else {
j ;
}
} else {
i--;
j = 0;
}
}
i tried the following at the end
else if(i != 0) {
i--;
j = 0;
}
CodePudding user response:
Add a second condition to your inner loop. That is, change
for (int j = 0; j < garage.size();) {
to
for (int j = 0; j < garage.size() && i >= 0;) {