The Eclipse IDE complains about the for loop using/accessing the array of books being out of bounds. The line (19) it complains about is: if (books[x] == null) {
I do not believe is the problem its complaining about as I have replaced that if code with many different things and it still complains. One line up is the first line of the for loop which is for (int x = 0; x < capacity ; ++x)
I have also triple checked the condition is right and it should be. capacity is 5 meaning the array of objects positions would be at 0, 1, 2, 3, 4 so starting x at 0 should be right from what I know about arrays.
Library Class (The one with the loop)
package exercises;
public class Library {
private int capacity;
private Book[] books = new Book[capacity];
public Library(int capacity) {
if (capacity > 1) {
this.capacity = capacity;
}
else {
this.capacity = 4;
}
}
public boolean addBook(Book book) {
int freeLocation = -1;
@SuppressWarnings("unused")
int notFreeLocation = -1;
for (int x = 0; x < capacity ; ++x) {
if (books[x] == null) { /*this is line 19*/
freeLocation = x;
}
else {
notFreeLocation = x;
}
}
if (freeLocation == -1) {
return false;
}
else {
books[freeLocation] = book;
return true;
}
}
The Library App class
package exercises;
public class LibraryApp {
public static void main(String[] args) {
// TODO Auto-generated method stub
Library library = new Library(5);
library.addBook(new Book("The Lord of the Rings", "J. R. R. Tolkien"));
library.addBook(new Book("Harry Potter and the Philosopher's Stone", "J. K. Rowling"));
library.addBook(new Book("1984", "George Orwell"));
library.addBook(new Book("Where the Wild Things Are", "Maurice Sendak"));
library.addBook(new Book("The Hitchhiker's Guide to the Galaxy", "Douglas Adams"));
System.out.println(library);
Book aBook = library.borrow("1984");
System.out.println("Book borrowed: " + aBook);
}
}
I get the error "Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0 at exercises.Library.addBook(Library.java:19) at exercises.LibraryApp.main(LibraryApp.java:8)