我正在尝试读取文件内容并将它们放入 vector 中并将其打印出来,但我遇到了一些问题,它重复打印内容!请帮忙看看我的代码有什么问题!谢谢!
这是我的代码:
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,浓缩粉末水,每包 2.50 美元
Z9983,反重力药丸,60 粒 12.75 美元
最佳答案
将for循环
移到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。如果你不关心线程安全,Vector的方法是使用ArrayList同步的(这是相当高效和快速的)
关于Java:将文件内容放入 vector 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14892524/