gpt4 book ai didi

java - 如何检查 Java 中 ArrayList 中是否找到元素?

转载 作者:行者123 更新时间:2023-12-01 10:06:36 26 4
gpt4 key购买 nike

我有一个 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com