2013-02-15 86 views
1

我试图读取文件内容,并将它们放在一个矢量中并打印出来,但是我在反复打印内容时遇到了一些问题!请帮忙看看我的代码有什么问题!谢谢!Java:将文件内容转换为矢量

这是我的代码:

public class Program5 { 
public static void main(String[] args) throws Exception 
     { 
      Vector<Product> productList = new Vector<Product>(); 

      FileReader fr = new FileReader("Catalog.txt"); 
      Scanner in = new Scanner(fr); 


      while(in.hasNextLine()) 
      { 

       String data = in.nextLine(); 
       String[] result = data.split("\\, "); 

       String code = result[0]; 
       String desc = result[1]; 
       String price = result[2]; 
       String unit = result[3]; 

       Product a = new Product(desc, code, price, unit); 

       productList.add(a); 

       for(int j=0;j<productList.size();j++)    
       {         
        Product aProduct = productList.get(j); 

        System.out.println(aProduct.code+", "+aProduct.desc+", "+aProduct.price+" "+aProduct.unit+" ");     
       } 

      } 

     } 

}

这是我想在阅读和它应该从我的代码打印文件的内容:

K3876 ,蒸馏月球,$ 3.00,一打
P3487,浓缩粉末水,每包2.50美元,
Z9983,抗重力丸,$ 12.75,为60

但是,这是我从运行的代码有:

K3876,蒸馏水月光,$ 3.00十几
K3876,蒸馏水月光,$ 3.00十几
P3487,浓缩粉的水,每包$ 2.50
K3876,蒸馏月光,$ 3.00十几
P3487,浓缩粉水,每包
Z9983 $ 2.50反重力丸,12.75 $ 60

+1

移动你的while循环外循环。 – 2013-02-15 10:20:39

+1

请勿使用矢量。它已经[过时了很久](http://stackoverflow.com/questions/1386275/why-is-java-vector-class-considered-obsolete-or-deprecated)现在。使用[ArrayList](https://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html)或类似的代替。 – ManoDestra 2016-07-27 19:34:52

回答

0

移动ŧ他在for-loop以外。

//外,同时

for(int j=0;j<productList.size();j++)    
       {        
       Product aProduct = productList.get(j);  
        System.out.println(aProduct.code+", "+aProduct.desc+", "+aProduct.price+" "+aProduct.unit+" ");     
       } 

顺便说一句,千万不要用向量,除非你关心线程安全。 Vector的方法是同步使用ArrayList(这是相当高效和快速),如果你不关心线程安全

+0

Eh,甚至担心线程安全我不会使用Vector来对比锁定或不同的同步集合/'Collections#synchronizedList' – Rogue 2016-07-31 23:27:05

0

for-loop放在while循环的一边。嵌套的循环打印冗余数据。

Vector<Product> productList = new Vector<Product>(); 
... 
while(in.hasNextLine()){ 
    ... 
    productList.add(a); 
} 
for(int j=0;j<productList.size();j++){ 
    .... 
} 
0

他们,你可以尝试移动 “的System.out.println(......)” 出的 “for” 循环:

while(in.hasNextLine()) 
{ 

    String data = in.nextLine(); 
    String[] result = data.split("\\, "); 

    String code = result[0]; 
    String desc = result[1]; 
    String price = result[2]; 
    String unit = result[3]; 

    Product a = new Product(desc, code, price, unit); 
    productList.add(a); 

    for(int j=0;j<productList.size();j++)    
    {         
     Product aProduct = productList.get(j);     
    } 
    System.out.println(aProduct.code+", "+aProduct.desc+", "+aProduct.price+" "+aProduct.unit+" "); 

}