我正在建立一个投票系统,用户使用他们的学号登录并进行选择。一旦有人投票,他们就无法再次登录。我做了一个对象;学生,包含学生编号的字符串和该学生编号是否已经投票的布尔值(均为私人)。我制作了一个这种类型的动态数组,以便通过使用扫描仪读取的文本文件接受给定数量的学生。但是,当我尝试填充对象数组中的学生编号字符串时,我得到一个NullPointerException。 Scanner IS从文本文件中读取信息,但是当我尝试将信息放入Student对象的私有字符串时发生错误。当我使用一个字符串数组时,一切正常,但我没有布尔值来判断某人是否已经投票。我对编程很陌生,不知道问题是什么。有人可以解释一下有什么问题以及如何修复它?
读取文本文件并填充数组的方法(学生是全局声明和构造的,最初的大小为0):
public static void getStudentNumbers(){
int a = 0;
while(fileReader.hasNext()){
if (a >= students.length)
{
int newSize = 1 + students.length;
Student[] newData = new Student[newSize];
System.arraycopy(students, 0, newData, 0, students.length);
students = newData;
}
students[a].setStudentNumber(fileReader.nextLine()); //Error occurs here
a++;
}
}
学生对象:
public class Student{
private Boolean hasVoted = false;
private String studentNumber = "";
public void setVotedStatus(Boolean voted){
hasVoted = voted;
}
public void setStudentNumber(String studentNum){
studentNumber = studentNum;
}
public Boolean getVotedStatus(){
return hasVoted;
}
public String getStudentNumber(){
return studentNumber;
}
}
错误:
java.lang.NullPointerException
at VotingSystem2_0.getStudentNumbers(VotingSystem2_0.java:279)
at VotingSystem2_0.main(VotingSystem2_0.java:245)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at edu.rice.cs.drjava.model.compiler.JavacCompiler.runCommand(JavacCompiler.java:272)
提前致谢!
答案 0 :(得分:3)
您忘记初始化新的Student
变量:
students = newData;
}
students[a] = new Student(); // not sure what your ctor is..
students[a].setStudentNumber(fileReader.nextLine()); //Error occurs here
a++;
顺便说一句,学生证书中是否包含除数字以外的其他内容?成为String
是否有意义? long
会更有意义吗? :)只是想一想。
哦,如果您这样做了,请使用Long#parseLong(String)
将String
转换为long
。
答案 1 :(得分:1)
替换
students[a].setStudentNumber(fileReader.nextLine());
与
students[a] = new Student();
students[a].setStudentNumber(fileReader.nextLine());