Hi guys. Java is really kicking my ass. I am taking this course online with no previous language experience and unfortunately I know no one that is proficient with Java. So here I am . Any assistance would be GREATLY appreciated. I am sorry if I posted this in the wrong forum. I am a newb.
Please let me give you the backdrop of my code.
Implement the findProduct method. This should look through the collection for a product whoose ID field matches the ID argument of this method. Id a matching product is found it should be returned as the method's result. If no matching product is found, return null.
When looking for a match, you will need to call the getID method on a product. This means that you will need to cast when you retrieve an item from the list.
I tried my best at trying to get it to work properly to return the requested product. However the best I could do is not enough. It keeps returning the null even if I put in a correct ID number and it returns a product even if I put in an incorrect ID number.
import java.util.ArrayList; import java.util.Iterator; /** * Manage the stock in a business. * The stock is described by zero or more Products. * * @author Matthew Wagner * @version 02 Feb 2010 */ public class StockManager { // A list of the products. private ArrayList stock; /** * Initialise the stock manager. */ public StockManager() { stock = new ArrayList(); } /** * Add a product to the list. * @param item The item to be added. */ public void addProduct(Product item) { stock.add(item); } /** * Receive a delivery of a particular product. * Increase the quantity of the product by the given amount. * @param id The ID of the product. * @param amount The amount to increase the quantity by. */ public void delivery(int id, int amount) { } /** * Try to find a product in the stock with the given id. * @return The identified product, or null if there is none * with a matching ID. */ public Product findProduct(int id) { int found = 0; Iterator it = stock.iterator(); while(it.hasNext()) { Product item = (Product) it.next(); System.out.println(""+item); found++; } if(found > 0) { return null; } else { return ((Product) it.next()); } } /** * Locate a product with the given ID, and return how * many of this item are in stock. If the ID does not * match any product, return zero. * @param id The ID of the product. * @return The quantity of the given product in stock. */ public int numberInStock(int id) { return 0; } /** * Print details of all the products. */ public void printProductDetails() { Iterator it = stock.iterator(); while(it.hasNext()) { System.out.println(it.next()); } } }