-1

I am trying to make an inventory system and am using the following code. I tried adding numberOfItems-- because I thought that was the problem but that doesn't seem to be it.

public static void delete(String title) {
    for(int i = 0; i < numberOfItems; i++) {
        if(newItem.get(i).getTitle().equalsIgnoreCase(title)){
            newItem.remove(i);
        }
    }
}
case 5:
    String name = "";
    System.out.println("What is the name of the item?");
    name = userInput.nextLine();
    delete(name);
    numberOfItems--;
    break;
b.GHILAS
  • 2,273
  • 1
  • 8
  • 16
Yuuya
  • 1
  • 3
    where does `numberOfItems` comes from ? – Nicolas Dec 13 '19 at 17:13
  • This may help https://stackoverflow.com/questions/5554734/what-causes-a-java-lang-arrayindexoutofboundsexception-and-how-do-i-prevent-it – Angela Amarapala Dec 13 '19 at 17:15
  • 2
    It's usually a bad idea to modify a collection while iterating through it. Or rather, it's a common source of bugs – byxor Dec 13 '19 at 17:15
  • 1
    You would also need to `i--`, but I'd suggest using an `Iterator` and their `.remove()` method instead. – Aaron Dec 13 '19 at 17:16
  • What does `newItem` consist of? Is it a List or an Array? Generally you should use an iterator for lists if you plan to modify them while looping/iterating over it. – Dennis B. Dec 13 '19 at 17:17
  • Add a break to the if condition once you remove the item. Should be fine then (Assuming you always input a correct "name" that exists on the list. Since you decrement numerOfItems without any validation) – saiftyfirst Dec 13 '19 at 17:27

1 Answers1

1

With newItem.remove(i) you're modifying that list (I guess it is a list, that's not clear from your example) while iterating over it. That's usually not a good idea.

There are different ways you could do this correctly. For example:

private static void delete(String title) {
    Iterator<ArrayElement> iterator = newItem.iterator();
    while (iterator.hasNext()) {
        if (iterator.next().getTitle().equalsIgnoreCase(title)) {
            iterator.remove();
        }
    }
}
tobi
  • 1,205
  • 2
  • 8
  • 8