我正在尝试读取文件内容,并将它们放入一个向量中,然后打印出来,但我遇到了一些重复打印内容的问题!请帮我看看我的代码出了什么问题!谢谢!
这是我的代码:
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美元,一打
P3487,浓缩粉末水,每包2.5美元
Z9983,反重力药丸,12.75美元,60美元
但这是我从运行代码中得到的:
K3876,蒸馏月光,一打3美元
K3876,蒸馏月光,一打3美元
P3487,浓缩粉末水,每包2.5美元
K3876,蒸馏月光,一打3美元
P3487,浓缩粉末水,每包2.5美元
Z9983,反重力药丸,60粒,12.75美元
发布于 2013-02-15 18:21:08
将for-loop移到外面,同时。
//外面的while
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同步Vector的方法(这非常高效且快速
发布于 2013-02-15 18:22:08
将for-loop放在while循环的外部。嵌套的for循环打印冗余数据。
Vector<Product> productList = new Vector<Product>();
...
while(in.hasNextLine()){
...
productList.add(a);
}
for(int j=0;j<productList.size();j++){
....
}发布于 2016-07-28 01:56:31
嗯,你可以试着移动"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+" ");
}https://stackoverflow.com/questions/14892524
复制相似问题