我对自己的处境感到很困惑。 我真的不确定为什么会出现这个空指针异常。
//这是我的一个类(class)的方法
public class UI {
Registry reg;
public UI (Registry reg) {
this.reg = reg;
menu();
}
private void addAppts(Scanner sc) {
System.out.println("Enter the month for appointment in mm/dd/yyyy format:");
sc.nextLine();
int month = sc.nextInt();
System.out.println("Enter the day for appointment mm/dd/yyyy format:");
sc.nextLine();
int day = sc.nextInt();
System.out.println("Enter the year for appointment mm/dd/yyyy format:");
sc.nextLine();
int year = sc.nextInt();
System.out.println("Enter the hour for appointment:");
sc.nextLine();
int hour = sc.nextInt();
System.out.println("Enter the minute for appointment:");
sc.nextLine();
int minute = sc.nextInt();
System.out.println("Enter the owner name for appointment:");
sc.nextLine();
String ownerName = sc.nextLine();
reg.addAppts(month, day, year, hour, minute, ownerName);
}
}
//这是我其他类(class)的另一个方法
public class Registry {
private Appointments[] appts;
public void addAppts(int month, int day, int year, int hour, int minute, String ownerName) {
if (next < appts.length) {
Appointments e = new Appointments(month, day, year, hour, minute, ownerName);
appts[next++] = e;
}
}
}
public class Appointments {
private int month, day, year, hour, minute;
private String ownerName;
public Appointments(int month, int day, int year, int hour, int minute, String ownerName) {
this.month = month;
this.day = day;
this.year = year;
this.hour = hour;
this.minute = minute;
this.ownerName = ownerName;
}
}
我在第一个方法的最后一行收到空指针异常错误。 有什么建议吗?
最佳答案
reg
很可能是 null
。
如果空值在概念上是允许的,则考虑在该方法周围使用 if (reg != null){
。如果该方法执行时它不应该为 null,则确保在构造对象时对其进行初始化。
关于java - java中用户输入后出现NullPointerException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22400746/