【发布时间】:2012-12-17 05:09:12
【问题描述】:
我有一个用于遍历数组列表的 for 循环,一旦找到我需要的对象,我想在该对象的 set 方法中设置先前获得的对象,为“未找到”设置一个标志为假,然后跳出循环。之后,如果未找到标志仍然为真,我想抛出异常,否则就到方法的结尾。
我认为我滥用了 break 或 for 循环。我经常抛出异常。
注意,'items' 是 LibraryItems 的数组列表。
for(LibraryItem l : items) {
if(l.equals(item)) {
l.setCheckedOut(patronToRetrieve);
itemNotFound = false;
break;
} else {
itemNotFound = true;
}
}
if (itemNotFound = true) {
throw new CheckInOutException("The item " + item.getTitle() + " does not exist in the catalogue. Sorry, " + patronToRetrieve.getName() + ", you will not be able to check this out at this time.");
} else {
}
【问题讨论】:
-
我相信你的意思不是 if (itemNotFound = true) use ==
-
您是否覆盖了
equals和hashCode? -
你不应该为 if 测试做 == 不 =
-
@Matt8541 是的,我是用 = 而不是 == 的假人
-
@Matt8541 itemNotFound 是布尔值,那么为什么要进行双重检查?