0

我正在学习 Java,我坚持这个例子

这是主要

package bookstore;

public class BookStore {


    public static void main(String[] args) {
        // create a Book object

        Book Java = new Book();
        Book Python = new Book();
        Book PHP = new Book();

        Java.name =  "Thinking In Java";
        Java.author = "Ahmad Ajmi";
        Java.canBorrow = true;
        Java.canReturned = true;
        Java.pagesNumber = 400;
        Java.publisher = "Oriely";
        String publish = Java.publishedDate(2013,4,5);

        System.out.println(publish);

        // Library.booksNumber works fine
        System.out.println("You have " + Library.booksNumber + " Books");

        // The problem is here
        System.out.println(Library.books);

    }
}

书类

package bookstore;

public class Book {

    // Defining book variables
    String name;
    String author;
    String publisher;
    int pagesNumber;
    int publisheddate;
    boolean canBorrow;
    boolean canReturned;

    public String publishedDate(int year, int month, int day) {
        return "" + year + " - " + month + " - " + day;
    }

    Book () {

        // Keep track of books created  
        Library.booksNumber += 1;

        // Here I want to push the book name into array
        for (int i = 0; i < Library.booksNumber; i++) {
            Library.books[i] = name;
        }

    }


}

图书馆类

package bookstore;

public class Library {

    static int booksNumber;

    // Array to push book names
    static String[] books;    

}

当我运行时出现此错误

Exception in thread "main" java.lang.NullPointerException
    at bookstore.Book.<init>(Book.java:23)
    at bookstore.BookStore.main(BookStore.java:9)
Java Result: 1

我想将书籍名称推送到 Library.books 数组中

4

1 回答 1

0

您需要初始化books数组。在课堂
上试试这个Book

Library.books = new String[Library.booksNumber];
for (int i = 0; i < Library.booksNumber; i++) {
        Library.books[i] = name;
    }
于 2013-09-17T20:02:46.357 回答