I want search for an object in an arraylist using one of it attribute: String name.
I have printed out Item Found here, and this works just fine.
public static void searchItems() {
// variable declaration
String itemSearch;
// collect value of variable using Scanner class
System.out.println("\t\tSEARCH ITEMS");
System.out.println("Enter item name: ");
itemSearch = input.next();
//search for an item
for (int i=0; i<itemList.size();i++) {
if (itemList.get(i).name.equalsIgnoreCase(itemSearch)) {
System.out.println("\t\t[ITEM FOUND]");
}
}
}
However, I want to notify when the item is not found as well. When I add else
to this for
loop, the String
itemSeacrh
gets matched (might not be the exact right term, sorry) with all the objects in the arraylist, and prints out the notification for every object index.
Let me explain. Suppose, objects: book, pen and pencil are stored in the ArrayList itemList
in that respective order and, the for
loop is modified the following way:
for (int i=0; i<itemList.size();i++) {
if (itemList.get(i).name.equalsIgnoreCase(itemSearch)) {
System.out.println("\t\t[ITEM FOUND]");
}
else {
System.out.println("\t\t[ITEM NOT FOUND]");
}
}
I want to search for the book. When I enter book as the itemSearch
the following get printed in the console:
SEARCH ITEMS
Enter item name:
book
[ITEM FOUND]
[ITEM NOT FOUND]
[ITEM NOT FOUND]
As you can see, it checks and prints that the book is not found in other objects, which in not what I exactly had in mind. I want it to print item found or either item not found, not both at the same time.
Thank you. I hope you understand my query.
Aucun commentaire:
Enregistrer un commentaire