I am writing a book class and a library class. the library class stores an array of books.
to simplify I am just providing the lines of code on which the error was produced.
if you would like the whole code please specify.
the error is on the if iteration.
am I using Objects.equals() incorrectly?
I am trying to compare bookname with books[x].title. if they are the same then it will mark the book as borrowed.
posted 3 years ago
I have tried bookname.equals(books[x].title)
I still get the same error
Exception in thread "main" java.lang.NullPointerException
Well, the problem is that your loop in borrowBook() is not idiomatic for 0-based indexed arrays. You wrote:
With 0-based indices, your termination condition should be x < maxBooks rather than x <= maxBooks. That's because if maxBooks is 1, the index for that book will be 0, if maxBooks is 2, the index for the last book will be 1, and so on. Since you don't terminate the for-loop immediately after finding the book you're looking for, you continue down to the end of the list and when you get to x = maxBooks, you've gone past the last book you have in your array and try to deference a null.
The best ideas are the crazy ones. If you have a crazy idea and it works, it's really valuable.—Kent Beck