I've been stuck with this java search statement.
I'm trying to search in an Array of Products called stock which is initialized in the class Stockmanager, which contains an id field a name and a stock level.
these product objects are made in a separate class called Product.
constructor Stockmanager:
// A list of the products.
private ArrayList<Product> stock;
/**
* Initialise the stock manager.
*/
public StockManager()
{
stock = new ArrayList<>();
}
Product constructor:
// An identifying number for this product.
private int id;
// The name of this product.
private String name;
// The quantity of this product in stock.
private int quantity;
/**
* Constructor for objects of class Product.
* The initial stock quantity is zero.
* @param id The product's identifying number.
* @param name The product's name.
*/
public Product(int id, String name)
{
this.id = id;
this.name = name;
quantity = 0;
}
There is an accessor method in Product to retrieve a product object id:
/**
* @return The product's id.
*/
public int getID()
{
return id;
}
Now in Stockmanager, I have my search method, but it seems this method will complain about incompatible datatypes if I don't use my for-each loop or will complain about not having a return statement if I do use a for-each loop.
the method:
/**
* 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 index = 0;
boolean searching = true;
for (Product item : stock)
{
while(searching && index < stock.size())
{
if (item.getID() == id)
{
searching = false;
return item;
} else {
index++;
}
if(searching)
{
return null;
} else {
return item;
}
}
}
}
It's got to be possible to have a while loop in this return statement because I don't need the method to look further in the array if it's found a hit.
Please, what am I doing wrong?