[Bluej-discuss] Chapter 4 Exercise 4.33
Michael Kölling
M.Kolling at kent.ac.uk
Fri Jul 7 15:33:35 BST 2006
On 7 Jul 2006, at 15:07, Marie Buchan wrote:
> Hi.
> Can anyone see why this code does not find a product? If an invalid
> id number is put in, the products which are there are returned
> instead of null being returned. If a valid id is searched for, it
> returns all the products.? Thanks again.
> Marie
>
> public Product findProduct(int id)
> {
> Iterator it = stock.iterator();
> while(it.hasNext()){
> Product product = (Product)it.next();
> if(product.getID() == id);{
> return product;
> }
> }
> return null;
> }
You fell into classic trap set for you by Java's sometimes strange
syntax rules. Look at these three of your lines:
> if(product.getID() == id);{
> return product;
> }
The problem is the semicolon after the if-condition. Unfortunately,
Java allows an if-statement without a body (technically: with an
empty body). It also allows a block (curly brackets) anywhere in a
statement sequence.
So what you have written is, in fact:
if(product.getID() == id);
{
return product;
}
Because of the semicolon, the if-part is not connected to the block.
So it will evaluate your if condition and do nothing. Then it will
(in any case) return the product.
Once you understand it, the fix is trivial:
if(product.getID() == id) {
return product;
}
Regards,
Michael
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://lists.bluej.org/pipermail/bluej-discuss/attachments/20060707/c0f7ddb3/attachment-0001.html
More information about the bluej-discuss
mailing list