-1

Calling a dlete method from the Book class from the main method gives a NullPointerException. Works fine when running the delete method from within the Main class.

Exception in thread "main" java.lang.NullPointerException at algorithms/algorithms.Main.main(Main.java:20)

What am I missing?

Main:

private static Book book;

public static void main(String[] args) {

    Book[] bookArray = {new Book(123, "Book1"), 
            new Book(321, "Book2"), 
            new Book(456, "Book3"), 
            new Book(654, "Book4"), 
            new Book(789, "Book5")};

    System.out.println(bookArray.length);
    bookArray = book.removeBook(bookArray, 456);
    System.out.println(bookArray.length);

    }

Book class method (left out attributes, getters and setters):

 public Book[] removeBook(Book[] books, int findISBN) {

    Book[] newArray = new Book[books.length - 1];
    int j = 0;

    for (int i = 0; i < books.length; i++) {
        if(books[i].getISBN() != findISBN) {
            newArray[j] = books[i];
            j++;
        }
    }
    return newArray;
}
anaximander
  • 357
  • 1
  • 5
  • 12

2 Answers2

3

You've declared a Book as a static but have not initialised it...

private static Book book;

When you do this...

bookArray = book.removeBook(bookArray, 456);

The book is null

Looks like you need to either...

  1. Assign a new Book() to your static Book
  2. You could make the method static in your Book class and call Book.removeBook(...) in your main method.
BretC
  • 4,141
  • 13
  • 22
1

You have only declared a reference to Book with private static Book book;. It needs to be instantiated before calling any methods on it. Include book = new Book(); inside main method.

It's also worth nothing that it is a bad design to include a resource and operations to be performed on the resource (in your case Book is the resource) in the same resource class.

It is much better to create another class like BookOperations and have all the logic written there, keeping your Book resource uncluttered and simple.

Andy Sug
  • 234
  • 2
  • 7