我正在尝试向我们展示一个很多的迭代器。我一直在收到“休息”的错误。线。它说这是一个无法达成的声明。任何帮助表示赞赏。
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");
}
}
}
答案 0 :(得分:8)
你如何期望从一个循环中脱离,然后在打破之后立即返回一些东西?
break;
return foundLot;
答案 1 :(得分:1)
它说return foundLot
无法访问,因为break
语句突破了循环(绕过return
)。
答案 2 :(得分:1)
它说中断后的行(return foundLot;
)是无法访问的语句。
答案 3 :(得分:1)
调用return
时无法访问break
。这是一个不使用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;
}
答案 4 :(得分:0)
将您的代码更改为:
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;
}