# Array iteration Problem.. Please help

Printable View

• November 23rd, 2012, 11:33 PM
learningjava1
Array iteration Problem.. Please help
Code java:

```Item[]items = new Item[4]; items[0]= new Item("n",2.2,4); items[0].setName("OJ"); items[0].setCost(6.00); items[0].setQty(10);   items[1]= new Item("n",2.2,4); items[1].setName("Milk"); items[1].setCost(3.99); items[1].setQty(20);   items[2]= new Item("n",2.2,4); items[2].setName("Snicker"); items[2].setCost(0.79); items[2].setQty(75);   items[3]= new Item("n",2.2,4); items[3].setName("Wheat Bread"); items[3].setCost(2.49); items[3].setQty(5);     items[0].getName(); items[0].getCost(); items[0].getQty();     items[1].getCost(); items[1].getName(); items[1].getQty();   items[2].getName(); items[2].getCost(); items[2].getQty();   items[3].getName(); items[3].getCost(); items[3].getQty();   Scanner scan = new Scanner(System.in); String input = scan.next(); for(int i=0; i<items.length; i++) { if(input.equals(items[i].getName())) { System.out.println("Item Found"); }   else { System.out.println("Item Not Found"); }   }```
The output is
Item Not Found
Item Found
Item Not Found
Item Not Found

It is comparing every ite
m in the array and printing the message. How can only have it print Item Found with out the other message. Please help me with this.
• November 24th, 2012, 12:18 AM
helloworld922
Re: Array iteration Problem.. Please help
hint: take a look at these lines of code.

Code java:

```for(int i=0; i<items.length; i++) { if(input.equals(items[i].getName())) { System.out.println("Item Found"); } else { System.out.println("Item Not Found"); } }```
• November 24th, 2012, 01:14 AM
learningjava1
Re: Array iteration Problem.. Please help
Im sorry I dont know how to fix it. I see that my if statement compare the input to every item in the list and then print out the message..
But i dun know how to fix it.

--- Update ---

Please let me know how i can fix it
• November 24th, 2012, 01:21 AM
C++kingKnowledge
Re: Array iteration Problem.. Please help
your code is saying every time it is in the for loop check the array element and print if the item is found or not so its going to print 4 times... u should make a method that returns true if the user input matches an item in the array.... you can then write an if statement in the main method that prints item found or not based on the results of the method.... that way it will only print one time
• November 24th, 2012, 01:55 AM
learningjava1
Re: Array iteration Problem.. Please help
It worked!! thank you!!!!