\n won't work, not going to a new line

試著忘記壹切 提交于 2020-01-11 05:40:29

问题


I'm creating a small program that saves a int value into a text file, saves it, and loads it when you start the program again. Now, I need 3 more booleans to be stored in the text file, I am writing things in the file with

    public Formatter x;

x.format("%s", "" + m.getPoints() + "\n");

Whenever I want to go to a new line in my text file, with \n, it wont go to a new line, it will just write it directly behind the int value. I tried doing both

        x.format("%s", "" + m.getPoints() + "\n");
    x.format("%s", "" + m.getStoreItem1Bought() + "\n");

and

    x.format("%s%s", "" + m.getPoints() + "\n", "" + m.getBought() + "\n");

but, both will just write the boolean directly behind the int value, without starting a new line. Any help on this?

I am using Windows 7 Ultimate 64 bits, and my text editor is Eclipse, I am running all of the code with Eclipse too.


回答1:


More specifically, I would recommend using:

x.format("%d%n%s%n", m.getPoints(), m.getStoreItem1Bought());



回答2:


Use this instead:

public static String newline = System.getProperty("line.separator");

Both of this options work. Your problem is in how you format the output:

System.out.format("%s" + newline + "%s" + newline, "test1", "test2");
System.out.format("%s%n%s", "test1", "test2");

Output:

test1
test2
test1
test2



回答3:


Try using %n instead of \n when using format. For details on this, please see the Formatter API and search this page for "line separator" and you'll see.




回答4:


No problem here:

System.out.format ("first: %s%s", "" + x + "\n", "" + y + "\n");

While I would prefere, to integrate the \n into the format String, not the values:

System.out.format ("second: %s\n%s\n", x, y);

Using Formatter.format works the same.




回答5:


Well your syntax is surely quite.. interesting. Why use the formatting method if you're just piece the string together anyways? Also since you nowhere say what stream you're using we have to guess a bit, but anyways.

Anyways I'm betting that 1. you're using windows and 2. that the editor (I bet on notepad) you're using only reacts to \r\n since that's the correct newline for Windows. To fix this DON'T hardcode \r\n in your code but instead use %n and use the printf function correctly (ie don't piece the string together!).

Otherwise if you really have to piece the string together:

String newline = System.getProperty("line.separator");
x.format("%s", "" + m.getPoints() + newline);

will work.



来源:https://stackoverflow.com/questions/5918139/n-wont-work-not-going-to-a-new-line

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!