如何检查在Java中的ArrayList中是否找到了元素?

时间:2016-04-04 16:00:31

标签: java arraylist

我有一个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,它将打印&#34;找不到&#34;或者其他的东西。有什么帮助吗?

1 个答案:

答案 0 :(得分:1)

显示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!");
    }
}