-2

I am working on a project given to me for classwork and we are modifying a library system that allows one to addpatrons to the library system, addbooks is already done for me and i have used that as a template to create addpatrons. I have completed it but whenever im trying to create it i get the following error.

 IndexOutOfBoundsException: Index -1 out of bounds for length 0

Here is where the code is going wrong.

public void execute(Library library, LocalDate currentDate) throws LibraryException {
    int lastIndex = library.getPatrons().size() -1;
    int maxId = library.getPatrons().get(lastIndex).getId();
    Patron patron = new Patron(++maxId, name, phone);
    library.addPatron(patron);
    System.out.println("Patron #" + patron.getId() + " added.");

The add patron takes in two values name and phone.

Thanks for your time

Curiosa Globunznik
  • 3,129
  • 1
  • 16
  • 24
Kazi Ilyas
  • 7
  • 1
  • 4

2 Answers2

0

When the size is 0, index-1 evaluates to -1. You can't access position 0, let alone -1, of an empty array.

You need to surround int lastIndex in code that makes sure your index is not equal to or less than the size of the array.

sleepToken
  • 1,866
  • 1
  • 14
  • 23
0

If library.getPatrons().size() is 0, your lastIndex is -1, which is not a valid index of any ArrayList. You should add an if statement that handles the case where the size of the list is 0.

chiragzq
  • 388
  • 1
  • 14