【发布时间】:2016-07-24 06:43:42
【问题描述】:
我有一个 arrayList,我想搜索一个特定的项目并对其执行如下操作:
System.out.print("What is the ID of the shop that you want to delete?");
int removedShopID= Integer.parseInt(in.next());
for(int i=0; i<shops.size(); i++){
if(shops.get(i).getID()==removedShopID)
{ shops.remove(i);
System.out.println("The shop has been successfully deleted.");}
}
}
它工作正常,但我需要添加一条语句,以防没有匹配的 ID,它将打印“未找到”或其他内容。有什么帮助吗?
【问题讨论】:
-
找到该项目时将布尔变量设置为 true。循环结束后,如果布尔变量未设置为 true,则打印“未找到”。
-
如果您按索引迭代列表并删除项目,请反向迭代。否则,您将跳过比赛后的项目。但最好使用
Iterator和Iterator.remove方法。 -
可能重复,问题已经回答here