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