I am trying to use a for loop to add elements to a LinkedList, and whenever I print the list it only contains one of my inputs, and has put it at every index.
I have a feeling the problem lies with my toString method, or with my Student constructor but can't seem to figure it out.
Any and all help is appreciated. Thanks!
import java.util.*;
public class Student {
private static String name;
private static String address;
private static double GPA;
static LinkedList<Student> stu = new LinkedList<Student>();
static Scanner scanner = new Scanner(System.in);
public Student(String name, String address, double GPA) {
Student.name = name;
Student.address = address;
Student.GPA = GPA;
}
public String getName() {
return Student.name;
}
public String getAddr() {
return Student.address;
}
public double getGPA() {
return Student.GPA;
}
public static void main(String [] args) {
for (int i = 0; i <= 2; i++) {
System.out.println("Enter the student's name: ");
name = scanner.next();
System.out.println("Enter the student's address: ");
address = scanner.next();
System.out.println("Enter the student's GPA: ");
GPA = scanner.nextDouble();
stu.addLast(new Student(name, address, GPA));
}
System.out.println(stu);
}
@Override
public String toString() {
String str = "Name: " + getName() + "\nAddress: " + getAddr() + "\nGPA: " + getGPA()+ "\n\n";
return str;
}
}
Console
Enter the student's name:
Jim
Enter the student's address:
111Ave
Enter the student's GPA:
2.3
Enter the student's name:
Joe
Enter the student's address:
222Ave
Enter the student's GPA:
3.0
Enter the student's name:
Jack
Enter the student's address:
333Ave
Enter the student's GPA:
3.4
[Name: Jack
Address: 333Ave
GPA: 3.4
, Name: Jack
Address: 333Ave
GPA: 3.4
, Name: Jack
Address: 333Ave
GPA: 3.4
]