正如本文中所推荐的:
https://stackoverflow.com/a/38077906/12340711
It's better to use %n as an OS independent new-line character instead of \n and it's easier than using System.lineSeparator()
但是,该功能对我不起作用:
\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
来格式化字符串在控制台输出之前。 java.util.Formatter
的所有详细信息可以在(Java 8 文档链接)找到: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
是整数,%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.out.*。请改用日志记录框架。
关于java - 使用 %n 作为新行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61050018/