0

我有以下从 main 调用的代码。代码的麻烦,它保存产品如下:1,ipad,499.0,ELECTRONICS

1,ipad,499.0,电子 2,Java 电子书,19.99,BOOK

我不明白第一个来自哪里。你能给我们一些建议吗?

非常感谢...

public void saveProductsToDisk() {

    String filename = "/Users/paddy/UCSC/Workspace/productDB/src/productdb/savedProducts.csv";
    BufferedWriter output = null;
    try 
    {
        output =  new BufferedWriter(new FileWriter(filename));
        StringBuffer line = new StringBuffer();
        for (Product p: getAllProducts())
        {
            line.append(p.getId() <=0 ? "" : p.getId());
            line.append(CSV_SEPARATOR);
            line.append(p.getName().trim().length() == 0? "" : p.getName());
            line.append(CSV_SEPARATOR);
            line.append(p.getPrice() < 0 ? "" : p.getPrice());
            line.append(CSV_SEPARATOR);
            line.append(p.getDept().toString());
            line.append("\n");
            output.write(line.toString());
        }
        output.flush();
        output.close();
    }
    catch (IOException ex)
    {
        System.out.println("IO error for " + filename +
                ": " + ex.getMessage());
    }
}
4

2 回答 2

1

line您在循环的每次迭代中重复使用相同的变量for

尝试在循环line顶部重新初始化,如下所示:for

...
StringBuilder line;
for (Product p: getAllProducts()) {
  line = new StringBuilder();
  line.append(p.getId() <=0 ? "" : p.getId());
  ...
于 2013-06-01T05:42:00.623 回答
1

用这个:

public void saveProductsToDisk() {

    String filename = 

"/Users/paddy/UCSC/Workspace/productDB/src/productdb/savedProducts.csv";
    BufferedWriter output = null;
    try 
    {
        output =  new BufferedWriter(new FileWriter(filename));
        StringBuilder line = null;
        for (Product p: getAllProducts())
        {
            line = new StringBuilder();
            line.append(p.getId() <=0 ? "" : p.getId());
            line.append(CSV_SEPARATOR);
            line.append(p.getName().trim().length() == 0? "" : p.getName());
            line.append(CSV_SEPARATOR);
            line.append(p.getPrice() < 0 ? "" : p.getPrice());
            line.append(CSV_SEPARATOR);
            line.append(p.getDept().toString());
            line.append("\n");
            output.write(line.toString());
        }
        output.flush();
        output.close();
    }
    catch (IOException ex)
    {
        System.out.println("IO error for " + filename +
                ": " + ex.getMessage());
    }
}
于 2013-06-01T05:43:36.180 回答