在线程“main”java.lang.NullPointerException中的Java Exception中将对象推送到数组中

时间:2013-09-17 20:00:25

标签: java nullpointerexception

我正在学习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数组

1 个答案:

答案 0 :(得分:0)

您需要初始化books数组 在Book

中试试这个
Library.books = new String[Library.booksNumber];
for (int i = 0; i < Library.booksNumber; i++) {
        Library.books[i] = name;
    }