【发布时间】:2020-07-27 13:11:51
【问题描述】:
我正在创建一个使用 2 个类的程序,一个创建一个使用 java.localdate 构造的具有姓名和生日的作者,另一个创建一个引用作者类的书。使用演示类我试图设置作者的生日,但是当我使用Month.JULY 设置月份时,我得到一个空指针异常,我不知道为什么。这是我的代码:
public class Book {
private String name;
private Author author;
private String ISBN;
private double price;
public Book(String name, Author author, double price, String ISBN) {
this.name = name;
this.author = author;
this.price = price;
this.ISBN = ISBN;
}
public String getName() {
return name;
}
public Author getAuthor() {
return author;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public String getISBN() {
return ISBN;
}
public void setISBN(String ISBN) {
this.ISBN = ISBN;
}
public String toString() {
return name + " by " + author + ISBN + price;
}
}
import java.time.LocalDate;
import java.time.Month;
public class Author {
private String firstname;
private String lastname;
private int year;
private Month month;
private int dayOfMonth;
LocalDate birthday = LocalDate.of( year, month, dayOfMonth);
public Author(String firstname, String lastname, int year, Month month, int dayOfMonth) {
this.firstname= firstname;
this.lastname= lastname;
this.year = year;
this.month = month;
this.dayOfMonth=dayOfMonth;
}
public String getFirstName() {
return firstname;
}
/** Returns the gender */
public String getLastName() {
return lastname;
}
/** Returns the email */
public int getYear() {
return year;
}
public Month getMonth() {
return month;
}
public int getdayOfMOnth() {
return dayOfMonth;
}
/** Returns a self-descriptive String */
public String toString() {
return firstname + " " + lastname + "(birthday:" + birthday + ")";
}
}
import java.time.Month;
import java.time.localDate:
//I tried with and without java.time.localDate
public class testBook {
public static void main(String[] args) {
Author jkr = new Author("JK","Rowling",1965,Month.JULY,31);
Book HPSS = new Book("Harry Potter and the Sorcerer's Stone", jkr, 11.99, "B017V4IMVQ" );
System.out.println(HPSS);
System.out.println(jkr);
}
}
【问题讨论】:
-
LocalDate birthday = LocalDate.of( year, month, dayOfMonth);抛出 NPE,因为month是null。 -
你需要在构造函数中将赋值移动到
birthday,因为字段初始化器在构造函数代码之前运行,所以month在你当前的代码中还没有被赋值。
标签: java nullpointerexception localdate