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 に答える