Hello I've got a problem with this program, it should store student information into an object of type Student. Stored information: last name, grade and votes. Votes are stored in an ArrayList of Integer. Every time I create a new object of type Student and I add it to an ArrayList of type Student (it stores all the students of a school), it keeps adding the new votes that I enter to the previous Student object created that it is already stored in the ArrayList.
EXAMPLE: I add a Student to the students ArrayList, I give in input freddy, 5b and 123 then i check the students ArrayList and it contains the student that i have already added: freddy,5b and 123. I add another student I give in input josh, 4t and 1234 I check
Why does it modify the object that is already created and stored in the ArrayList? How can i fix it?
Here's the code:
public class Student {
private String lastname;
private String grade; // example "4b"
private ArrayList<Integer> student_votes;
public Student(String lastname, String grade, ArrayList<Integer> student_votes) {
this.lastname=lastname;
this.grade=grade;
this.student_votes=student_votes;
}
public ArrayList getVotes() {
return student_votes;
}
public String getLastname() {
return lastname;
}
public String getGrade() {
return grade;
}
public String toString() {
return lastname+" "+grade+" "+getVotes();
}
public void print_student (Student student) {
System.out.println(student);
}
public static void print_students(ArrayList<Student> students) {
for(Student s : students) {
System.out.print(s);
}
System.out.println("");
}
public static void menu() {
System.out.println("\nPress 1 to add a student\nPress 2 to remove a student\nPress 3 to print the classroom\nPress 4 to exit");
}
public static void main(String[] args) {
int choice, nv=0, i=0,average=0;
Boolean exit=false;
ArrayList<Student> students = new ArrayList<Student>();
ArrayList<Integer> votes = new ArrayList<Integer>();
String lastname = new String();
String grade = new String();
Scanner sc = new Scanner(System.in);
Scanner st = new Scanner(System.in);
do {
menu();
choice=sc.nextInt();
switch (choice) {
case 1: System.out.println("Enter your lastname:");
lastname=st.nextLine();
System.out.println("Enter your grade:");
grade=st.nextLine();
System.out.println("Enter the amount of votes");
nv=sc.nextInt();
for(i=0;i<nv;i++) {
System.out.println("Enter vote n:"+(i+1));
votes.add(sc.nextInt());
}
students.add(new Student(lastname,grade,votes));
System.out.println("student added!");
break;
case 2: System.out.println("Enter student position: ");
nv = sc.nextInt();
students.remove(nv-1);
break;
case 3: print_students(students);
break;
case 4: exit = true;
}
} while (exit==false);
}
}