2016-10-14 1 views
0
추가 한 이유

안녕하세요 모두 난 자바 초보자 해요, 난이 자바 코드를 작성하고 다음과 같습니다내 자바 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)); 
     } 



    } 

} 

내가 예를 들어 세 학생을 추가 할 때 : (banash, 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