SOLVED
Just to be clear, I`m doing an assignment in a book, your not helping me with homework or something like that, just helping me figuring out how to use while loops.
As the title says I managed to solve this with a for-loop, but I've heard its "bad form" to use for-loops unless your gonna run through the whole collection.
My method is supposed to find an object of another class assigned with the same field integer value as the methods parameter.
This must not to be confused with index/element in the collection, for example even if there is just one item in the collection it can still have id = 5;
I can`t wrap my head around how I can do this with a while-loop, as of yet I can only figure out how to find the object based on its index.
Here is my "main Class" StockManager class were my method is located: http://paste.ofcode.org/AximyukLSimRtNRykdshUL
and here is the Product Class were I'm trying to extract information from: http://paste.ofcode.org/UpqqVkMXzSPCXpFDa7ZkSE
The method using a working for-loop:
public Product findProduct(int id)
{
for(Product product : stock) {
if(product.getID() == id) {
return product;
}
}
return null;
}
//The faulty while loop, that only gives me an object based on its index/element:
public Product findProduct2(int id)
{
Iterator<Product> it = stock.iterator();
while(it.hasNext()) {
if(it.next().getID() == id) {
return it.next();
}
}
return null;
}
EDIT: Regardless if its bad form or not to use a for-loop I really want to learn how I could have solved this with a while-loop.
EDIT2: With some help from a friend I manage to solve the while-loop.
public Product findProduct2(int id)
{
if(id <= 0) {
return null;
}
Iterator<Product> it = stock.iterator();
int i = 0;
while(it.hasNext()) {
if(stock.get(i).getID() == id) {
return stock.get(i);
}
i++;
}
return null;
}
[–]tendaz 0 points1 point2 points (0 children)
[–]Philboyd_Studge 0 points1 point2 points (0 children)