如何避免for循环中索引i低于0导致程序崩溃?
如何避免循环中索引低于0导致崩溃?
原逻辑是遍历vehicles和garage,检查车辆与车库是否处于同一空间:若不匹配,则递减i(车辆循环索引)以获取下一辆可用车辆,但当i到0时会继续降到-1,触发索引越界导致程序崩溃。
原代码
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; } } }
你尝试的修改
else if(i != 0) { i--; j = 0; }
正确解决思路与修改方案
问题核心是当i=0时,进入else分支仍会执行i--,直接让索引变为-1。要解决这个问题,需仅在i > 0时允许递减i,同时当i=0且找不到匹配车库时,直接终止外层循环(已遍历完所有车辆)。
修改后的代码:
for (int i = vehicles.size() - 1; i >= 0;) { boolean foundGarage = false; 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--; foundGarage = true; break; } else { j++; } } else { // 仅当i大于0时才递减索引,否则退出内层循环 if (i > 0) { i--; } else { foundGarage = false; break; } j = 0; } } // 若i为0且未找到匹配车库,直接终止外层循环 if (i == 0 && !foundGarage) { break; } }
更清晰的优化写法
可以改用while循环拆分索引控制逻辑,避免嵌套条件混乱,从根源上防止索引越界:
int i = vehicles.size() - 1; while (i >= 0) { boolean processed = false; for (int j = 0; j < garage.size(); j++) { var vehicle = vehicles.get(i); var garageSpot = garage.get(j); if (garageSpot.getSpace() == vehicle.getSpace()) { if (garageSpot.garageRequest(vehicle.getvehiclesType()) && garageSpot.getLimit() > 0) { garageSpot.addvehicles(vehicle); vehicles.remove(i); processed = true; break; } } } // 未找到合适车库时,仅在i>0时递减索引 if (!processed) { if (i == 0) break; i--; } else { // 移除车辆后,根据业务需求决定是否递减索引(此处保持原逻辑) i--; } }
内容的提问来源于stack exchange,提问作者Joseph Martínez
相关产品推荐
相关产品推荐

