Вопрос

For instance, I have:

    private List<Entry> entries = new LinkedList<Entry>();

@Override
public void addEntry(Entry entry) {
    entries.add(entry);
    Collections.sort(entries);
}

@Override
public void deleteEntry(String input) throws IllegalArgumentException {
    for (int i = 0; i < entries.size(); i++) {
        if (entries.get(i).getName().equalsIgnoreCase(input) || entries.get(i).getExtension().equalsIgnoreCase(input)) {
            entries.remove(i);
        }
    }
}

I have performed testing on this code and it works perfectly fine. As soon as I add an else block to throw an exception in my delete method, the method keeps always throwing exceptions when it is called.

@Override
public void deleteEntry(String input) throws IllegalArgumentException {
    for (int i = 0; i < entries.size(); i++) {
        if (entries.get(i).getName().equalsIgnoreCase(input) || entries.get(i).getExtension().equalsIgnoreCase(input)) {
            entries.remove(i);
        } else {
            throw new IllegalArgumentException();
        }
    }
}

The above code throws exceptions even if the input is incorrect. Do you have any idea about this? Thank you

Это было полезно?

Решение

You are throwing an exception if there is an entry which doesn't match.

You should check the input before you start the loop and only throw an IAE if the input is invalid. You shouldn't need a loop for this check.

Другие советы

you need to add "break" after entries.remove(i);

Your method will throw an exception unless the condition is met for every entry in the list.

public void deleteEntry(final String input) throws IllegalArgumentException
  {
    for (int i = 0; i < entries.size(); i++)
    {
      if (entries.get(i).getName().equalsIgnoreCase(input) || entries.get(i).getExtension().equalsIgnoreCase(input))
      {
        entries.remove(i);

        return;
      }
    }

    throw new IllegalArgumentException();
  }

This should work, if your intention is find the first entry match the condition and remove, and throw exception if it is not found.Your method will not work except all entries match your condition.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top