List<Student> studentInfo = new LinkedList<Student>();
int choice;
boolean flag = true;
Student student = new Student();
while(flag)
{
System.out.println();
System.out.println("Press 1 to Add Student details");
System.out.println("Press 2 to Display Student details");
System.out.println("Press 3 to Sort");
System.out.println("Press 4 to Search");
System.out.println("Press 5 to Exit");
System.out.println("Enter your choice: ");
choice = sc1.nextInt();
switch(choice)
{
case 1: studentInfo.add(student.addDetails());
break;
case 2: System.out.println("Details of Students are as follows: ");
for(Student s : studentInfo){
System.out.println(s);
}
break;
//More code
Student 类中的 addDetails() 方法是:
public Student addDetails()
{
System.out.println("Enter the name: ");
name = sc2.nextLine();
this.setName(name);
return this;
}
我正在使用案例 1 块获取学生详细信息,然后将它们添加到 studentInfo 集合中。但是,当我显示最后输入的详细信息时,会覆盖所有以前的详细信息,当我打印出来时,只会显示我添加的学生数量。有人可以告诉我我做错了什么吗?谢谢!
输出:学生的详细信息如下:name=Amar,age=0,term=0,sub_1_marks=0,sub_2_marks=0,sub_3_marks=0,percentage=0,totalMarks=0 name=Amar,age=0,term= 0,sub_1_marks=0,sub_2_marks=0,sub_3_marks=0,百分比=0,totalMarks=0