up vote 2 down vote favorite
share [g+] share [fb]

I am getting a null pointer when I run this piece of code. Its self-explanatory , two classes are used to model a Book and a Library.

I would appreciate it if someone can tell me where I am going wrong.

public class Library {


    private String address;
    private final static String workinghours = "9AM to 5PM";
    private Book[] bookcollection = new Book[6];
    private static int numberofbooks = 0;

    public Library(String libraryaddress) {
        address = libraryaddress;
    }

    public static void printOpeningHours() {
        System.out.println(workinghours);
    }

    public void addBook(Book newaddition) {
        bookcollection[numberofbooks] = newaddition;
        numberofbooks++;
    }

    public void printAddress() {
        System.out.println(address);
    }

    public void borrowBook(String bookname) {
        for (int i = 0; i < bookcollection.length; i++) {

            if (bookcollection[i].getTitle().equals(bookname)&&(!(bookcollection[i].isBorrowed()))) 
            {
                bookcollection[i].borrowed();
                break;
            }

        }

    }

    public void returnBook(String bookname) {
        for (int i = 0; i < bookcollection.length; i++) {

            if (bookcollection[i].getTitle().equals(bookname)) {
                bookcollection[i].returned();
                break;
            }

        }

    }

    public void printAvailableBooks() {
        for (int i = 0; i < bookcollection.length; i++) {

            if (!(bookcollection[i].isBorrowed())) {
                System.out.println(bookcollection[i].getTitle());
            }

        }

    }

    public static void main(String[] args) {
        // Create two libraries
        Library firstLibrary = new Library("10 Main St.");
        Library secondLibrary = new Library("228 Liberty St.");

        // Add four books to the first library
        firstLibrary.addBook(new Book("The Da Vinci Code"));
        firstLibrary.addBook(new Book("Le Petit Prince"));
        firstLibrary.addBook(new Book("A Tale of Two Cities"));
        firstLibrary.addBook(new Book("The Lord of the Rings"));

        // Print opening hours and the addresses
        System.out.println("Library hours:");
        printOpeningHours();
        System.out.println();

        System.out.println("Library addresses:");
        firstLibrary.printAddress();
        secondLibrary.printAddress();
        System.out.println();

        // Try to borrow The Lords of the Rings from both libraries
    /*  System.out.println("Borrowing The Lord of the Rings:");
        firstLibrary.borrowBook("The Lord of the Rings");
        firstLibrary.borrowBook("The Lord of the Rings");
        secondLibrary.borrowBook("The Lord of the Rings");
        System.out.println();*/

        // Print the titles of all available books from both libraries
        System.out.println("Books available in the first library:");
        firstLibrary.printAvailableBooks();
        System.out.println();
        System.out.println("Books available in the second library:");
        secondLibrary.printAvailableBooks();
        System.out.println();

        // Return The Lords of the Rings to the first library
        System.out.println("Returning The Lord of the Rings:");
        firstLibrary.returnBook("The Lord of the Rings");
        System.out.println();

        // Print the titles of available from the first library
        System.out.println("Books available in the first library:");
        firstLibrary.printAvailableBooks();
    }
}

 

//Library uses objects of class book as members  

public class Book {

    String title;
    boolean borrowed;

    // Creates a new Book
    public Book(String bookTitle) {

        title = bookTitle;
        borrowed = false ;
    }

    // Marks the book as rented
    public void borrowed() {

        borrowed = true;
    }

    // Marks the book as not rented
    public void returned() {

        borrowed = false;
    }

    // Returns true if the book is rented, false otherwise
    public boolean isBorrowed() {

        return ((borrowed) ? true : false);

    }

    // Returns the title of the book
    public String getTitle() {

        return title;
    }

    public static void main(String[] arguments) {
        // Small test of the Book class
        Book example = new Book("The Da Vinci Code");
        System.out.println("Title (should be The Da Vinci Code): "
                + example.getTitle());
        System.out.println("Borrowed? (should be false): "
                + example.isBorrowed());
        example.borrowed();
        System.out.println("Borrowed? (should be true): "
                + example.isBorrowed());
        example.returned();
        System.out.println("Borrowed? (should be false): "
                + example.isBorrowed());
    }
}
link|improve this question

38% accept rate
2  
Two comments: Where do you get the NPE? and, Please try to accept some of the answers to your previous questions. – aioobe Jan 30 '11 at 14:36
you can look at your stack and which line throw the exception. – Aba Dov Jan 30 '11 at 14:38
I like the parking lot analogy. Think of an array of objects like a parking lot. You must fill it with cars (objects) before you can try to drive one of the cars (use one of the objects). And I too second the comment above that you should go back through your questions and accept some answers. This will encourage others to help you in the future. – Hovercraft Full Of Eels Jan 30 '11 at 14:46
feedback

3 Answers

up vote 2 down vote accepted

Try changing all loops that look like

for (int i = 0; i < bookcollection.length; i++) {

to

for (int i = 0; i < numberofbooks; i++) {

As it stands now, you will try to do bookcollection[i].getTitle() on an entry in the books-array that has not yet been assigned a value (that is, still contains null).

link|improve this answer
thanks , i realized my mistake. I guess avoiding null pointer exceptions requires good programming. i now have used numberofbooks in the for loop and also have an if clause when numberofbooks==0 -> "no book in catalog". – maverick Jan 30 '11 at 14:56
Yes, I saw that, that's why I didn't bother to write a long and explaining answer :-) – aioobe Jan 30 '11 at 15:37
feedback

When you create an array of books with private Book[] bookcollection = new Book[6];, each Book in the array is initially null. So, when you loop through the array without checking for null, you will get a NullPointerException. One place this will happen is in printAvailableBooks():

for (int i = 0; i < bookcollection.length; i++) {
    if (!(bookcollection[i].isBorrowed())) { // NPE if bookcollection[i] is null!
        ....

To fix this, loop over numberofbooks, which should match the number of non-null books.

link|improve this answer
feedback

One more point that I believe has to be noted is that

numberofbooks

should not be a static variable. This is because, it will be common to firstLibrary and secondLibrary.

Say you have added 4 books in firstLibrary and then you add a book in secondLibrary, it is stored in the 5th position of the array. Thereby 1st four indices of secondLibrary contains a null and 5th index contains a book.

Another problem that can arise due to this is ArrayIndexOutofBoundException.

link|improve this answer
yes I understood that, I changed it while revising the code. Good catch nonetheless. – maverick Feb 1 '11 at 9:10
feedback

Your Answer

 
or
required, but never shown

Not the answer you're looking for? Browse other questions tagged or ask your own question.