简体   繁体   中英

cannot figure out why this test is failing here in adding a item to ArrayList

method code here:
public boolean addItem(MediaItem item)
    {
        for (int count = 0; count < Library.size(); count++){
        String callNum = Library.get(count).getCallNumber();
            if(item.getCallNumber().compareToIgnoreCase(callNum) == 0)
        {
          while( item.getCopyNumber() < Library.get(count).getCopyNumber())
          {
            int copyNum = item.getCopyNumber();
            copyNum++;
            item.setCopyNumber(copyNum);
           } 
           Library.add(item);
           return true;
           
        } else if (item.getCallNumber().compareToIgnoreCase(callNum) != 0)
        {
            item.setCopyNumber(1);
            Library.add(item);
            return true;
        }
       
    }
           
        return false;
      
    }
testCases:
    public void testAddItem(){
        AnytownLibrary newlib = new AnytownLibrary();
        assertNotNull(newlib);
        MediaItem newItem = new Book();
        MediaItem nextItem = new Book();
        
        assertNotNull(nextItem);
        assertNotNull(newItem);
        newItem.setCallNumber("1");
        nextItem.setCallNumber("1");
        newlib.addItem(newItem);
        assertTrue(newlib.addItem(newItem));
        newlib.addItem(nextItem);
        assertTrue(newlib.addItem(nextItem));
        
        
      
}

I cannot figure out why this is failing it keep throwing a assertion error here, and its not telling me that its just the output is false so im unsure whats wrong i have completely tested my get and set methods and they are correct; and a version of this that just asserts that the (itemname) rather than call numbers return true passed previously, so I'm sure the answer is somewhere in the method itself

Your logic for adding an item to library is wrong. Adding the very first item will always fail, because the for loop with not execute as the size is zero. So nothing will happen. Since this fails all the subsequent addItem calls will also fail. There are many what to do this, a simple way will be to check if size is zero and add to the list directly and return. Else use ur for loop.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM