0

So, basically I have a library system that has

    private int numberOfBooks = 0;

    public int getNumberOfBooks()
{
    return numberOfBooks;
}

Of course when you add a new book in the library the numberOfBooks is increased by 1. My other class Student has the following code:

    private LibrarySystem libraryBooks;

    public void searchByISBN()
{
    int i = 0;
    boolean found = false;
    while(i<libraryBooks.getNumberOfBooks()) //THE PROBLEM IS HERE
    {
        if(books[i].getISBN().equals(in.next()))
        {
            found = true;
            break;
        }
        i++;
    }
    if(found)
    {
        System.out.println("\n Book info: \n ISBN: " + books[i].getISBN() + 
                            "\n Title: " + books[i].getTitle() +
                            "\n Author: " + books[i].getAuthor() +
                            "\n Subject: " + books[i].getSubject());
                        }
       else System.out.println("There is no book with such ISBN");
}

I get a Java.lang.NullPointerException and I don't know why. How can I fix this?

aefea21
  • 1
  • 2
  • `libraryBooks` appears to be null. Fix it -- initialize the variable before using it. If you've done even a little searching on solving a NullPointerException (NPE), you'll know that the most important bit of information that we need is the exception's associated stacktrace and some identification of the line that causes it, something that the stacktrace will tell you. – Hovercraft Full Of Eels Apr 05 '15 at 23:40
  • **You should critically read your exception's stacktrace to find the line of code at fault, the line that throws the exception, and then inspect that line carefully**, find out which variable is null, and then trace back into your code to see why. You will run into these again and again, trust me. – Hovercraft Full Of Eels Apr 05 '15 at 23:41

1 Answers1

0

In your function, put the following:

libraryBooks = new LibrarySystem();

Because you have not initialized it, libraryBooks is null

burmat
  • 2,548
  • 1
  • 23
  • 28