尝试制作一个简单的基于控制台的地址簿。第一种方法是我的“加载”方法,它从文本文件中获取数据。但是,它会抛出这样的错误:
Exception in thread "main" java.lang.NullPointerException
at pack.AddressBook.load(AddressBook.java:18)
at pack.AddressBook.main(AddressBook.java:33)
我的AddressBook类看起来像这样:
public class AddressBook {
public static Student [] load() throws FileNotFoundException{
Scanner input = new Scanner(System.in);
System.out.println("Which file do you want to access?");
String filename = input.nextLine();
Scanner fileScanner = new Scanner(new File(filename));
Student [] studentArray = new Student[1];
int i = 0;
while(fileScanner.hasNextLine()){
studentArray[i].firstName = fileScanner.nextLine();
studentArray[i].lastName = fileScanner.nextLine();
studentArray[i].age = fileScanner.nextLine();
studentArray[i].grade = fileScanner.nextLine();
i++;
System.out.println(i);
}
return null;
input.close();
fileScanner.close();
return studentArray;
}
public static void main(String[] args) throws entryError, FileNotFoundException {
Student [] studentsInCurrentBook = load();
}
}
我的学生班看起来像这样(如果重要的话):
public class Student {
public String firstName;
public String lastName;
public String age;
public String grade;
public Student() throws entryError{
throw new entryError("Please provide at least a first and last name.");
}
public Student(String firstName, String lastName){
this.firstName = firstName;
this.lastName = lastName;
age = "unknown";
grade = "unknown";
}
public Student(String firstName, String lastName, String age){
this.firstName = firstName;
this.lastName = lastName;
this.age = age;
grade = "unknown";
}
public Student(String firstName, String lastName, String grade, char i){
this.firstName = firstName;
this.lastName = lastName;
age = "unknown";
this.grade = grade;
}
public Student(String firstName, String lastName, String age, String grade){
this.firstName = firstName;
this.lastName = lastName;
this.age = age;
this.grade = grade;
}
}
student.txt文件的格式如下:
firstname
lastname
age
grade
谢谢!
答案 0 :(得分:0)
Student [] studentArray = new Student[1];
int i = 0;
while(fileScanner.hasNextLine()){
studentArray[i].firstName = fileScanner.nextLine();
studentArray[i].lastName = fileScanner.nextLine();
studentArray[i].age = fileScanner.nextLine();
studentArray[i].grade = fileScanner.nextLine();
i++;
System.out.println(i);
}
因此,您创建一个大小为1的空数组,然后尝试在其i
元素中设置字段。
在开始访问studentArray [i]字段之前,您需要创建一个学生进入您的数组。在您这样做之前,null
是您阵列中的唯一内容,这就是您获得NullPointerException
的原因。
然后你需要确保你的数组有足够的长度来容纳你添加的所有学生(所以你最好使用ArrayList)。
答案 1 :(得分:0)
基本上你没有在studentArray
中添加任何学生你只创建了一组Student
个对象,然后尝试访问索引Student
的{{1}}这当然是空的。您需要做的是添加i
然后添加studentArray[i] = new Student();
循环或只是执行此操作:
while
或者这个:
studentArray[i] = new Student(fileScanner.nextLine(), fileScanner.nextLine(), fileScanner.nextLine(), fileScanner.nextLine());
等等......希望这是有道理的