为什么我的java LinkedList被添加了相同的值

时间:2016-10-14 21:01:38

标签: java

大家好我是java初学者,我写了这个java代码,它看起来像这样:

import java.util.LinkedList;
import java.util.Scanner;

public class Main {

    public static void main(String[] args)
    {
        LinkedList <Student>  l1 = new LinkedList<Student>();

        Scanner sc = new Scanner(System.in);

        Student e1 = new Student();

        int i=0;
        int choice;
        String name;
        String cne;

        do
        {

            System.out.println("Student name "+i);

            name = sc.nextLine();
            e1.setName(name);


            System.out.println("Student CNE "+i);
            cne = sc.nextLine();
            e1.setCne(cne);

            System.out.println(e1);

            l1.add(e1);


            System.out.println("type 1 to continue, other to quit : ");

            choice = sc.nextInt();

            sc.nextLine();

            i++;

        }while( choice == 1 );


        for ( i=0 ; i < l1.size() ; i++)
        {

            System.out.println(l1.get(i));
        }



    }

}

当我添加三个学生时:(banash,001)(victor,002)(lykke,003)

我得到了这个结果:

lykke => 003
lykke => 003
lykke => 003

有谁能告诉我问题在哪里!

1 个答案:

答案 0 :(得分:1)

您需要在循环中初始化Student对象。目前e1只是一个对象,您正在循环中更新其值。并在列表中添加相同的对象

public class Main {
    public static void main(String[] args) {
        LinkedList <Student>  l1 = new LinkedList<Student>();
        Scanner sc = new Scanner(System.in);

        int i=0;
        int choice;
        String name;
        String cne;

        do {
            Student e1 = new Student();
            System.out.println("Student name "+i);

            name = sc.nextLine();
            e1.setName(name);

            System.out.println("Student CNE "+i);
            cne = sc.nextLine();
            e1.setCne(cne);

            System.out.println(e1);

            l1.add(e1);

            System.out.println("type 1 to continue, other to quit : ");
            choice = sc.nextInt();
            sc.nextLine();
            i++;
        }while( choice == 1 );


        for ( i=0 ; i < l1.size() ; i++) {
            System.out.println(l1.get(i));
        }
    }
}