【问题标题】:How to check if element was found in an ArrayList in Java?如何检查是否在 Java 的 ArrayList 中找到元素?
【发布时间】: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,则打印“未找到”。
  • 如果您按索引迭代列表并删除项目,请反向迭代。否则,您将跳过比赛后的项目。但最好使用IteratorIterator.remove 方法。
  • 可能重复,问题已经回答here

标签: java arraylist


【解决方案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!");
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-03-09
    • 2016-03-19
    • 2011-11-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-07
    相关资源
    最近更新 更多