My program reads a text file with student information and puts each line of data into a new Student object with various properties.
A loop then puts each of those Student objects into an ArrayList, allowing the student data to be searched using other methods.
However, the only way I have been able to make this work is to call the readStudent method in each search method, meaning the input file is processed and the ArrayList recreated repeatedly.
This is the method which reads the input file, creates the objects and puts the objects in the ArrayList:
public class readStudent
{
public static List< Student > readStudent() throws Exception {
Scanner input = new Scanner(new File("students.txt"));
List< Student > studentList = new ArrayList< Student >();
while (input.hasNext()) {
int id = input.nextInt();
String lastName = input.next();
String firstName = input.next();
int gradYear = input.nextInt();
Student student = new Student(id, firstName, lastName, gradYear);
studentList.add(student);
}
return studentList;
}
This is one of the search methods, also in the readStudent class (slightly edited for brevity):
public static void allRecords() throws Exception {
List< Student > studentList = readStudent.readStudent();
int size = studentList.size();
for (int i=0; i<size; i++) {
System.out.printf("%-5d %10s %10s %15d\n", studentList.get(i).returnId(), studentList.get(i).returnFirst(), studentList.get(i).returnLast(), studentList.get(i).returnGrad());
}
}
The other search methods all begin with List< Student > studentList = readStudent.readStudent(); to make the array available to be searched.
My question is this: Is it possible to perform the readStudent method once to create the ArrayList, perhaps in the beginning of main, then reference that ArrayList from the search methods without having to re-run the entire readStudent method every time?