Michael Caine
Michael Caine

Reputation: 1

unreachable statement - break;

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

Answers (5)

Chandu
Chandu

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

Kaleb Brasee
Kaleb Brasee

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

Greg
Greg

Reputation: 33650

It's saying that the line after the break (return foundLot;) is an unreachable statement.

Upvotes: 1

Bert F
Bert F

Reputation: 87603

It says that return foundLot is unreachable because of the break statement breaks out of the loop (bypassing the return).

Upvotes: 1

Falmarri
Falmarri

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

Related Questions