2016-10-14 5 views
0

こんにちは私は誰もJavaの初心者で追加された理由は、私はこのJavaコードを書き、それが次のようになります。私は、例えば3人の学生を追加するとき私のjavaのLinkedListは同じ値

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



    } 

} 

001)(ビクター、002)(lykke、003)

私は、結果としてこれを取得する:problemeです

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

誰も私に教えてもらえます!

答えて

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

ありがとうございます – sicario123

関連する問題