I'm making a student system with console based java. I'm trying to load a text file's content to an ArrayList and later on search with a student registration number and list down his/her name and program. I'm having a hard time loading the text file contents in an ArrayList so that I can retrieve them later on as objects.
I have made a search function that works perfectly on an Arraylist (Since when entering a new record I am putting them in ArrayList and they can be searched until the program is not shut)
This is the approach I am using trying to load the text file in an ArrayList:
try {
ArrayList<NewStudent> student = new ArrayList<>();
BufferedReader inFile = new BufferedReader (new FileReader
("Test.txt"));
String inputLine;
while ((inputLine = inFile.readLine())!=null) {
NewStudent ns = new NewStudent();
String[] studentVars = inputLine.split(":");
ns.setName(studentVars[0]);
student.add(ns);
}
System.out.print(student);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
This is my approach in searching and this works like a charm
public Student Search(String ID, ArrayList<Student> StudentList)
{
Student myStudent = new Student();
for(int i=0 ; i<StudentList.size() ; i++)
{
if(StudentList.get(i).getID().equals(ID))
{
myStudent.setID(StudentList.get(i).getID());
myStudent.setName(StudentList.get(i).getName());
myStudent.setProgram(StudentList.get(i).getProgram());
return myStudent;
}
}
return null;
}
**When it prints, it prints this:**
[com.Student.NewStudent@615e7597, com.Student.NewStudent@7a3e72, com.Student.NewStudent@5999ae9c, com.Student.NewStudent@7896b1b8, com.Student.NewStudent@6d6de4e1, com.Student.NewStudent@49cda7e7, com.Student.NewStudent@5cca548b]
** And if I use a different approach that is:**
BufferedReader inFile = new BufferedReader (new FileReader
("Student.txt"));
ArrayList<String> arrayList = new ArrayList<>();
String inputLine;
while ( (inputLine = inFile.readLine() ) != null) {
String[] stud = inputLine.split(":");
arrayList.add(stud[0]); \\if I add stud[1] it gives null pointer exception
}
System.out.println(arrayList);
This doesn't return as separate objects. it shows one straight line