2017-04-26 70 views
0

我正在处理一个java项目,并且卡住了。我试图找出如何首先存储具有几个元素(如名,姓和ID)的人物对象。我知道可以为对象的每个部分创建不同的集合,但是我想知道是否可以创建和查询一个集合中的所有元素?也就是说,在将对象存储在集合中之后,我想通过集合来查找名字,姓氏和ID。存储和查询集合中的对象java

这是我当前的代码:

public static void processRecords(String filenameIn)throws Exception{ 
    Scanner input = new Scanner(new File("students_mac.txt")); //retrieves data from file and stores 
    input.nextLine(); 

    while (input.hasNextLine()) { //enters loop to process individual records and print them 
      String line = input.nextLine(); 
      String[] tokens=line.split("\t"); // splits lines by tabs 
      if(tokens.length!=4) 
       continue; 
      Person student = new Person(FirstName, LastName, ID, Year); 
      List<Person> list = new LinkedList<Person>(); 
      list.add(student); 
     } 

    List<Person> list=new LinkedList<Person>(); 
     for(Person student : list){ 
      System.out.println(student); 
     } 
+0

你只需要移动你的'LinkedList'的声明和初始化了'while'循环之外,也删除它下面的一个。 –

回答

0

所有你需要的是将List<Person> list = new LinkedList<Person>();出while循环。

Scanner input = new Scanner(new File("students_mac.txt")); //retrieves data from file and stores 
input.nextLine(); 

List<Person> list = new LinkedList<Person>(); 

while (input.hasNextLine()) { //enters loop to process individual records and print them 
     String line = input.nextLine(); 
     String[] tokens=line.split("\t"); // splits lines by tabs 
     if(tokens.length!=4) 
      continue; 
     list.add(new Person(FirstName, LastName, ID, Year)); 
    } 

    for(Person student : list){ 
     System.out.println(student); 
    }