0

hello everybody i'm java beginner, i wrote this java code and it looks like this:

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));
        }



    }

}

when i add three Student for example : (banash,001) (victor,002) (lykke,003)

i get this as a result :

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

Could anyone please tell me where is the probleme !

sicario123
  • 15
  • 1
  • 4

1 Answers1

1

You need to initialize Student object within the loop. Currently e1 is just a single object and you are updating its values in the loop. And adding the same object in the list

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));
        }
    }
}
sidgate
  • 14,650
  • 11
  • 68
  • 119