0

I have an arrayList and I want to search for a specific item and perform an action on it like so:

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.");}

                         }


}

It is working fine but I need to add a statement in case of no ID matched it will print " not found" or something. any help?

Amal
  • 37
  • 1
  • 5
  • 7
    Set a boolean variable to true when you find the item. After the loop, if the boolean variable was not set to true, print "not found". – khelwood Apr 04 '16 at 16:01
  • 3
    If you are iterating a list by index and removing items, iterate in reverse. Otherwise you will skip the item following a match. But it is better to use an `Iterator` and the `Iterator.remove` method. – Andy Turner Apr 04 '16 at 16:03
  • possible duplicate, question already answered [here](http://stackoverflow.com/questions/10714233/remove-item-from-arraylist) – faizanjehangir Apr 04 '16 at 16:09

1 Answers1

1

To show what khelwood means:

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!");
    }
}
PendingValue
  • 252
  • 1
  • 12