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");
        }
    }
}
How do you expect to break from a loop, and then right after breaking from it, return something?
break;
return foundLot;
It says that return foundLot is unreachable because of the break statement breaks out of the loop (bypassing the return).
It's saying that the line after the break (return foundLot;) is an unreachable statement.
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;
}
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;   
} 
 
         加载中,请稍侯......
 加载中,请稍侯......
      
精彩评论