尝试使用break在获得所需值后退出for循环 - 总是抛出异常

Ben*_*nny 0 java for-loop arraylist

我有一个for循环,我用来遍历arraylist,一旦我找到了我需要的对象,我想在这个对象的set方法中设置一个先前获得的对象,将'not found'的标志设置为false然后突破循环.之后,如果未找到标志仍然为真,我想抛出异常,否则只是到了方法的末尾.

我想我要么滥用中断还是for循环.我一直在抛出异常.

注意,'items'是LibraryItems的arraylist.

        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 {

        }
Run Code Online (Sandbox Code Playgroud)

kos*_*osa 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.");
        } 
Run Code Online (Sandbox Code Playgroud)

上面的语句总是产生true,因为你要分配trueitemNotFound的if语句.

应该:

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.");
        } 
Run Code Online (Sandbox Code Playgroud)

(要么)

 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.");
            } 
Run Code Online (Sandbox Code Playgroud)

==是equaulity检查,=是分配.