Исключение нулевого указателя Java при использовании массива объектов - PullRequest
2 голосов
/ 30 января 2011

Я получаю нулевой указатель, когда запускаю этот кусок кода.Это само за себя, два класса используются для моделирования книги и библиотеки.

Буду признателен, если кто-нибудь скажет мне, где я иду не так.

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());
    }
}

Ответы [ 3 ]

3 голосов
/ 30 января 2011

Когда вы создаете массив книг с private Book[] bookcollection = new Book[6];, каждый Book в массиве изначально равен null.Итак, когда вы перебираете массив без проверки на null, вы получите NullPointerException.Одно из мест, где это произойдет, находится в printAvailableBooks():

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

. Чтобы исправить это, выполните цикл по numberofbooks, который должен соответствовать количеству не null книг.

2 голосов
/ 30 января 2011

Попробуйте изменить все циклы, которые выглядят как

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

на

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

В нынешнем виде вы попытаетесь сделать bookcollection[i].getTitle() для записи в массиве книгкоторому еще не было присвоено значение (то есть все еще содержит ноль).

0 голосов
/ 30 января 2011

Еще один момент, на который, я полагаю, следует обратить внимание, это то, что

NUMBEROFBOOKS

не должно быть статической переменной. Это потому, что это будет общим для firstLibrary и secondLibrary.

Допустим, вы добавили 4 книги в firstLibrary, а затем добавили книгу во secondLibrary, она сохраняется в 5-й позиции массива. Таким образом, первые четыре индекса secondLibrary содержат ноль, а пятый индекс содержит книгу.

Другая проблема, которая может возникнуть из-за этого, - ArrayIndexOutofBoundException.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...