Reputation: 1
I'm trying to us an iterator to show a lot. I keep getting an error with the "break;" line. It says it is an unreachable statement. Any help is appreciated.
public Lot getLot(int number) {
Lot foundLot = null;
Iterator it = lots.iterator();
while (it.hasNext()) {
Lot b = (Lot) it.next();
if (b.getNumber() == number) {
foundLot = b;
break;
return foundLot;
} else {
System.out.println("lot " + number + " does not exist");
}
}
}
Upvotes: 0
Views: 2807
Reputation: 82943
Change your code to as follows:
public Lot getLot(int number)
{
Lot foundLot = null;
Iterator it=lots.iterator();
while(it.hasNext())
{ Lot b=(Lot) it.next();
if(b.getNumber() == number) {
foundLot = b;
break;
}
else {
System.out.println("lot "+number + " does not exist");
}
}
return foundLot;
}
Upvotes: 0
Reputation: 51965
The return
is unreachable when the break
is called. This is an alternate version that does not use the break:
public Lot getLot(int number) {
Lot foundLot = null;
Iterator it=lots.iterator();
while(it.hasNext() && foundLot == null) {
Lot b=(Lot) it.next();
if(b.getNumber() == number) {
foundLot = b;
}
}
if (foundLot == null) {
System.out.println("lot "+number + " does not exist");
}
return foundLot;
}
Upvotes: 1
Reputation: 33650
It's saying that the line after the break (return foundLot;
) is an unreachable statement.
Upvotes: 1
Reputation: 87603
It says that return foundLot
is unreachable because of the break
statement breaks out of the loop (bypassing the return
).
Upvotes: 1
Reputation: 48597
How do you expect to break from a loop, and then right after breaking from it, return something?
break;
return foundLot;
Upvotes: 8