I am making a voting system where the user logs in with their student number and makes a selection. Once someone has voted, they cannot be able to log in again. I made an object; Students, containing a String for the student number and a boolean for whether or not that student number has already voted (both being private). I made a dynamic array of this type as to accept a given amount of students off of a text file that is read through the use of a Scanner. However, when I try to populate the student number string within the object array, I get a NullPointerException. The Scanner IS reading the information from the text file, but the error occurs when I try to put the information into the private string of the Student object. When I use an array of strings everything works fine, but then I don't have the boolean to tell whether or not someone has already voted. I am quite new to programming and have no idea what the problem is. Can someone please explain what is wrong and how it can be fixed?
Method where text file is read and array is populated(students is declared and constructed globally, initially having the size of 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++;
}
}
Student Object:
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;
}
}
Error:
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)
Thanks in advance!
studentsinitialized properly? Could you please post the code where you initializestudents?students[a]must be null.ArrayList<Student>, rather than aStudent[]. Theadd(...)method will handy that nasty array-copying and expansion for you, and it will run much faster (your current algorithm is O(N^2), not O(N))