簡體   English   中英

使用 %n 作為新行

[英]Using %n as new line

正如這篇文章中所推薦的那樣:
https://stackoverflow.com/a/38077906/12340711

最好使用 %n 作為獨立於操作系統的換行符而不是 \n 並且比使用 System.lineSeparator() 更容易

但是,function 對我不起作用:

\n :

System.out.println("foo\nbar");
>>>foo
>>>bar

正常工作。

%n :

System.out.println("foo%nbar");
>>>foo%nbar

不解釋。

有人可以解釋一下為什么%n對我不起作用嗎? 它可能不再受支持還是我錯過了什么?

Java 為您提供System.lineSeparator()常量。 如果您使用的是println ,那將以獨立於操作系統的方式打破界限。 如果您只是在玩代碼,也可以在字符串中使用\n來換行。 它既簡單又快速。 請注意, println只是將純文本打印到控制台。

當您使用printf時,您實際上將使用java.util.Formatter在控制台 output 之前格式化字符串。 All details of the java.util.Formatter can be found at (Java 8 docs link): https://docs.oracle.com/javase/8/docs/api/java/util/Formatter.html

因此,如果要使用println格式化字符串,則需要先使用java.util.Formatter對其進行格式化,例如:

String formattedStr = String.format("%s = %d %n hello", "joe", 35);
System.out.println(formattedStr);

其中%s是字符串, %d是 integer 數字和%n換行符(在上面的文檔鏈接中描述)。

printf只是上述兩行代碼的快捷方式,其中String.format已經在printf實現中。

System.out.printf("%s = %d %n hello", "joe", 35);

您還可以在printf字符串中使用\n

System.out.printf("%s = %d \n hello", "joe", 35);

最后,重要的是要了解,在現實世界的項目中,如果您不使用java.util.Formatter (在Formatter中,使用%n ),您應該始終使用System.lineSeparator()而不是\n 此外,您永遠不應該將System.out.*用於實際項目。 請改用日志框架。

%nSystem.out.println()解釋為String

要使用%n ,您必須使用System.out.printf() ,就像您發布的示例一樣。

注意\nSystem.out.printf()解釋為newline

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM