简体   繁体   English

如何使用printwriter将数据写入输出文件[保留]

[英]how to write data to output file using printwriter [on hold]

        PrintWriter out = new PrintWriter(outputFile);

        String result = "";

        for (Orders o : allOrders) {
            result += o + "\n";
            out.print(result);
        }

this is what i have so far and the result to the file should look like: 这是我到目前为止的内容,文件的结果应如下所示:

pizza

hamburger

sandwich

quesadilla

but when i ran my test cases it said that line 2 was actually "pizza", so basically I'm wondering if my code is somehow incorrect? 但是当我运行测试用例时,它说第2行实际上是“比萨饼”,因此基本上我想知道我的代码是否不正确?

UPDATE: so it passed now i was forgetting out.close() lol 更新:所以它过去了,现在我忘记了out.close()大声笑

Here is your code: 这是您的代码:

  String result = "";

    for (Orders o : allOrders) {
        result += o + "\n";
        out.print(result);
    }

At the end of the first loop, Result is pizza\\n. 在第一个循环结束时,结果为披萨\\ n。 After the second time, it's pizza\\nhamburger\\n. 第二次之后,是披萨\\汉堡\\ n。

So you'll print: 因此,您将打印:

pizza <-- from the first print
pizza <-- start of second print
hamburger
pizza <-- start of third print
hamburger
sandwich
pizza <-- start of fourth print
hamburger
sandwich
quesadilla

The problem is the +=. 问题是+ =。 Change it to a simple = and see how that works. 将其更改为简单的=并查看其工作原理。

You could simply do this: 您可以简单地做到这一点:

PrintWriter out = new PrintWriter(outputFile);

for (Orders o : allOrders) {
    out.print(o + "\n");
}

If you want two returns like your output that you gave shows, you can simply add another "\\n". 如果您想要两个返回值,例如您显示的输出,则只需添加另一个“ \\ n”即可。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM