我有一个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匹配,我需要添加一条语句,它将显示“未找到”或类似内容。有什么帮助吗?
最佳答案
展示khelwood的含义:
public static void main(String[] args) {
List<Shop> shops = new LinkedList<Shop>();
System.out.print("What is the ID of the shop that you want to delete?");
Scanner scanner = new Scanner(System.in);
int removedShopID = scanner.nextInt();
boolean isFound = false;
for (int i = 0; i < shops.size(); i++) {
if (shops.get(i).getID() == removedShopID) {
shops.remove(i);
isFound = true;
System.out.println("The shop has been successfully deleted.");
}
}
if (!isFound) {
System.out.println("Not found!");
}
}
关于java - 如何检查元素是否在Java的ArrayList中找到?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/36407493/