1

ファイルの内容を読み込んでベクターに入れて印刷しようとしていますが、内容が繰り返し印刷されるという問題があります。私のコードの何が問題なのかを確認するのを手伝ってください! ありがとうございました!

これは私のコードです:

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、凝縮粉末水、1 パケットあたり $2.50
Z9983、アンチグラビティ ピル、$12.75、60 個

しかし、これは私がコードを実行して得たものです:

K3876、蒸留ムーンビーム、1 ダース 3.00 ドル
K3876、蒸留ムーンビーム、1 ダース 3.00 ドル
P3487、凝縮粉末水、1 パケットあたり 2.50 ドル
K3876、蒸留ムーンビーム、1 ダース 3.00 ドル
P3487、凝縮粉末水、1 パケットあたり 2.50
ドル60用

4

3 に答える 3

0

em、「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+" ");

}
于 2016-07-27T17:56:30.997 に答える
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 を使用しないでください。スレッドの安全性を気にしない場合は、Vector のメソッドが同期されます(非常に効率的で高速な) ArrayListを使用します。

于 2013-02-15T10:21:08.190 に答える
0

for-loopwhile ループの外側に置きます。ネストされた for ループは、冗長データを出力します。

Vector<Product> productList = new Vector<Product>();
...
while(in.hasNextLine()){
   ...
   productList.add(a);
}
for(int j=0;j<productList.size();j++){
   ....
}
于 2013-02-15T10:22:08.073 に答える