2016-11-25 73 views
1

我正在尝试创建客户对象的链接列表,但我不完全知道如何去填充列表。当我运行程序时,什么也没有发生,程序似乎陷入了while循环?我真的不知道填充对象的链表(程序运行时什么都没有发生)

这里是我的客户类

public class Customer { 
    private String name; 
    private String address; 
    private String num; 
    private int year; 

    public Customer(String name, String address, String num, int year) { 
     this.name = name; 
     this.address = address; 
     this.num = num; 
     this.year = year; 
    } 
    @Override 
    public String toString() { 
     return "Name: " + name + "\nAddress: " + address + "\nCustomer Number: " + num + "\nLast Order: " + year; 

} 
} 

,这里是我的测试类:

import java.io.FileNotFoundException; 
import java.util.Scanner; 
import java.io.File; 
import java.util.*; 

public class CustomerRunner { 
    public static void main(String[] args) throws FileNotFoundException { 
     String name; 
     String address; 
     String num; 
     int year; 
     Customer customer; 

     LinkedList<Customer> lst = new LinkedList<Customer>(); 

     Scanner in = new Scanner(new File("Customers.txt")); 
     Scanner input = new Scanner(System.in); 

     while(in.hasNext()) { 
      for (int i = 0; i < lst.size(); i++){ 
       name = in.next(); 
       address = in.next(); 
       num = in.next(); 
       year = in.nextInt(); 

       customer = new Customer(name, address, num, year); 
       System.out.println(customer.toString()); 
      //fill linkedList 
      lst.add(customer); 
      } 
     } 
     System.out.println("1"); 
     System.out.println(lst.size()); 

} 
} 

中的println(1)和println(lst.size())仅在那里尝试获得某种输出。

供参考,这是我的Customers.txt移动

Brooke MainStreet 123456789 2016 
Adam MainStreet 234567890 2015 
Zack MainStreet 123412341 2014 
Cam MainStreet 453648576 2010 
Tanya MainStreet 121212121 2005 
Jason MainStreet 556574958 2004 
Andrew MainStreet 777777777 2012 
John MainStreet 999999999 2015 
Jeff MainStreet 555444321 2010 

回答

1

您的循环永远不会循环。 ArrayList,lst最初没有项目,所以当for循环运行时它的大小是0。外部while循环不断重复,因为扫描器永远不会因for循环失败而放弃任何标记。相反,根本不要使用for循环,而只是使用while循环来检查扫描器对象何时用完了令牌。

例如,

while (in.hasNextLine()) { 
     String line = in.nextLine(); 

     // I scan here the line obtained, but also could split the String 
     // if desired 
     Scanner lineScanner = new Scanner(line); 
     String name2 = lineScanner.next(); 
     String addr2 = lineScanner.next(); 
     String num2 = lineScanner.next(); 
     int year2 = lineScanner.nextInt(); 
     lineScanner.close(); 

     Customer cust2 = new Customer(name2, addr2, num2, year2); 
     lst.add(cust2); 
    } 
+0

@Brooke:看到编辑 –

相关问题