0

我有一个用于遍历数组列表的 for 循环,一旦找到我需要的对象,我想在该对象的 set 方法中设置先前获得的对象,将“未找到”的标志设置为 false 和然后跳出循环。之后,如果未找到标志仍然为真,我想抛出异常,否则就到方法的结尾。

我想我要么滥用了 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 {

        }
4

1 回答 1

6

我可以看到的一个问题是:

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.");
        } 

上面的语句总是导致,因为你在if 子句true中赋值。trueitemNotFound

应该:

if (itemNotFound) {
            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.");
        } 

(或者)

 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.");
            } 

==是平等检查,=是赋值。

于 2012-12-17T05:10:40.367 回答