2013-02-15 87 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+" "); 

}