My task is to extract all the records from a text file (which has 2 columns-name and manager name- and 9 rows), create an Employee object from each record ( name and manager), and then add the employee object to an ArrayList that accepts Employee objects.
For some reason, when I attempt to loop through the list later on, it seems as if the last record is what is being stored for all of the records.
Below is my code. I even put some print line statements to make sure that token was the correct name and manager name right before they get added, but again, when I loop through it afterwards all the records show up as "Veronica and Bob".
Here is the text file:
Betty Sam
Bob Sally
Dilbert Nathan
Joseph Sally
Nathan Veronica
Sally Veronica
Sam Joseph
Susan Bob
Veronica
Here is my method:
List<Employee> employees = new ArrayList();
public void loadData() throws FileNotFoundException, IOException {
FileReader fr = new FileReader("C:\\Users\\jeff\\Documents\\NetBeansProjects\\Java3Project1\\src\\java3project1\\employee.txt");
BufferedReader br = new BufferedReader(fr);
String line;
Employee e = new Employee();
while ((line = br.readLine()) != null) {
StringTokenizer st = new StringTokenizer(line);
int counter = 0;
while (st.hasMoreTokens()) {
String token = st.nextToken();
if (counter==0){
e.setName(token);
System.out.println("Name added: " + token);
}
if (counter == 1) {
e.setManager(token);
System.out.println("Manager set: " + token);
}
employees.add(e);
counter++;
}//end while2
}//end while1
} //end loadData()
When I check the list after this method was called, all the records come out as Name: Veronica Manager: Bob
I cant seem to figure out what I am doing wrong. All help is greatly appreciated. Let me know if you have any questions or need more clarification.
Thank you!