gpt4 book ai didi

java - 创建实例时出现空指针异常

转载 作者:行者123 更新时间:2023-12-01 23:02:58 25 4
gpt4 key购买 nike

我有一个异常,我不知道如何解决它。

Person a = new Person();
Scanner in = new Scanner(System.in);
System.out.println("Please type name: ");
String name = in.nextLine();

它说第一行有一个异常。以下代码是默认构造函数。

Person(){
this.name = "No_Name";
this.surname = "No_Surname";
this.number = "No_Number";
this.personalCode = "No_personalCode";
this.dateOfBirth.set(Calendar.DAY_OF_MONTH, 1);
this.dateOfBirth.set(Calendar.MONTH, Calendar.JANUARY);
this.dateOfBirth.set(Calendar.YEAR, 1900);
}

类(class)人员完整代码:

import java.util.Calendar;
public class Person {
String name;
String surname;
private String number;
private String personalCode;
private Calendar dateOfBirth;



Person(){
this.name = "No_Name";
this.surname = "No_Surname";
this.number = "No_Number";
this.personalCode = "No_personalCode";
this.dateOfBirth.set(Calendar.DAY_OF_MONTH, 1);
this.dateOfBirth.set(Calendar.MONTH, Calendar.JANUARY);
this.dateOfBirth.set(Calendar.YEAR, 1900);
}
Person(String name,String surname,String number,String personalCode,Calendar dateOfBirth){
this.name = name;
this.surname = surname;
this.number = number;
this.personalCode = personalCode;
this.dateOfBirth = (Calendar) dateOfBirth.clone();

}

Person setName(Person a, String name) {
a.name = name;
return a;
}
Person setSurname(Person a, String surname) {
a.surname = surname;
return a;
}
Person setNumber(Person a, String number) {
a.number = number;
return a;
}
Person setpersonalCode(Person a, String personalCode) {
a.personalCode = personalCode;
return a;
}

String getName(Person a) {
return a.name;
}
String getSurname(Person a) {
return a.surname;
}
String getNumber(Person a) {
return a.number;
}
String getPersonalCode(Person a) {
return a.personalCode;
}
Calendar getDateOfBirth(Person a) {
return a.dateOfBirth;
}
}

最佳答案

您正在对空字段 (dateOfBirth) 调用 set()

可能的解决方法:

Date date = new GregorianCalendar(1900, Calendar.FEBRUARY, 1).getTime();
this.dateOfBirth = date;

关于java - 创建实例时出现空指针异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58414594/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com