Hello,
I'm refactoring a C++ program into a Java program (yes, it's homework). I have a problem where I add objects to an ArrayList of type Student, but when I try to access the objects, every valid index returns what should be only in the last element.
For the sake of brevity, I'm posting my code with most of the irrelevant parts removed. I'll be happy to post the whole thing if there isn't enough to go on here.
package project5;
import java.io.*;
import java.util.*;
public class StudentAction
{
ArrayList<Student> student = new ArrayList<Student>();
Scanner s;
// other class variable declarations
public void LoadStudents()
{
// code to check existence and readbility of target file: seems to work
while (s.hasNextLine())
{
// code to load data from file with Scanner object - seems to work
// code to put the assembled subclasses into the Student object
// prints correct values here
System.out.println(tempPerson.getLastName());
// this assembles the sub objects into each Student object
// in the student ArrayList
student.add(new Student(tempPerson, tempCompDate, gpa, credits));
//prints correct values here
System.out.println(student.get(counter).getPerson().getLastName());
System.out.println(counter);
counter++;
} // end while
for (int a = 0; a < student.size(); a++)
{
// returns the value that should be in
// in the last element 50 times.
// there should be 50 elements, but they
// should have mostly different values
System.out.println(student.get(a).getPerson().getLastName());
}
} // end function LoadStudents
// other functions
} // end class StudentAction
I hope someone can show me where I've erred. Thank you.