Search code examples
javaoopobjectfor-loopremove-if

achieving the same result but using a different kind of loop


so this method performs daily checks that adds one day to the displayedDays in order to determine the freshness of an item, so the method adds a day then check if it's rotten by calling the method isRotten() and if it's rotten it removes it the array

    for (int i = 0; i < numItems; i++) {
        items[i].displayedDays++;
    }

    for (int i = 0; i < numItems;) {

        if (items[i].isRotten()) {
            if (removeItem(i)) {
                if (i > 0) {
                    i--;
                }
                continue;
            }
        }

        i++;
    }

this is also another method that uses the same loop and if's so this method is supposed to remove the sweets from the array ( the array has two types of items bread and sweets)

    double totalSweetsPrice = 0;

    int count = numItems;

    for (int i = 0; i < count;) {
        Item item = items[i];

        if (item instanceof Sweet) {
            totalSweetsPrice += item.getPrice();
            if (removeItem(i)) {
                if (i > 0) {
                    i--;
                }
                continue;
            }
        }
        i++;
    }

and I don't understand the middle part and was hoping that there is a different loop or something whilst getting the same result

this was how a wrote the daily check method

    for (int i = 0; i < numItems; i++) {
    items[i].displayDays++ ;
    if(items[i].isRotten())
    removeItem(i); }

and the output was wrong


Solution

  • As FooBar said, you can’t both iterate an ArrayList and remove items from that same ArrayList. So you need to separate the conditions. For example:

    for (int i = 0; i < items.size(); i++) {
        items.get(i).displayedDays++;
    }
    
    int i = 0:
    while (i < items.size()) {
        if(items.get(i).isRotten()) {
            items.remove(i);
            // don’t increment our counter here because now 
            // we’ve changed what object exists in the ArrayList 
            // at this index position
        } else {
            // only increment our counter if the item in that index
            // is good, so we can now move on to check the next item
            i++;
        }
    }