换行打印,java

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4008223/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 08:16:33  来源:igfitidea点击:

Print in new line, java

javaprintingnew-operatorprintln

提问by Upvote

I have following code :

我有以下代码:

    System.out.println(" | 1  2  3  4  5  6  7  8  9");
    System.out.println("----------------------------");
    System.out.println("");

I use println to create a new line. Is it possible to do the same using \n or \r? I tried to add \n to the second println statment and continue printing with the print method but \n does not create a new line.

我使用 println 创建一个新行。是否可以使用 \n 或 \r 来做同样的事情?我尝试将 \n 添加到第二个 println 语句并继续使用 print 方法打印,但 \n 不会创建新行。

any ideas?

有任何想法吗?

采纳答案by Jigar Joshi

    String newLine = System.getProperty("line.separator");//This will retrieve line separator dependent on OS.

    System.out.println("line 1" + newLine + "line2");

回答by biasedbit

It does create a new line. Try:

它确实创建了一个新行。尝试:

System.out.println("---\n###");

回答by James Branigan

You might try adding \r\n instead of just \n. Depending on your operating system and how you are viewing the output, it might matter.

您可以尝试添加 \r\n 而不仅仅是 \n。根据您的操作系统以及您查看输出的方式,这可能很重要。

回答by vstoyanov

Your best shot would be with

你最好的镜头是

String.format("%n")

or

或者

System.out.printf("%n");

It is supposed to print a newline character, depending on the current platform, so it's perfect for the console.

它应该根据当前平台打印换行符,因此它非常适合控制台。

If you are printing to a file, then it depends.

如果要打印到文件,则视情况而定。

回答by Salahuddin

\ncreates a new line in Java. Don't use spaces before or after \n.

\n在 Java 中创建一个新行。不要在 之前或之后使用空格\n

Example: printing It creates\na new lineoutputs

示例:打印It creates\na new line输出

It creates
a new line.

它创建
了一个新行。

回答by tushar

Since you are on Windows, instead of \n use \r\n (carriage return + line feed).

由于您在 Windows 上,而不是 \n 使用 \r\n (回车 + 换行)。

回答by Shawn Vader

You should use the built in line separator. The advantage is that you don't have to concern what system you code is running on, it will just work.

您应该使用内置的行分隔符。优点是你不必关心你的代码在什么系统上运行,它会正常工作。

Since Java 1.7

从 Java 1.7 开始

System.lineSeparator()

Pre Java 1.7

Java 1.7 之前的版本

System.getProperty("line.separator")

回答by Santhosh Raja

"\n" this is the simple method to separate the continuous String

"\n" 这是分隔连续字符串的简单方法

回答by Santhosh Raja

System.out.println("hello"+"\n"+"world");

回答by Bhavya Jain

//Case1:
System.out.println(" 1  2  3  4  5  6  7  8  9" + "\n" + "----------------------------");

//Case2:
System.out.printf(" 1  2  3  4  5  6  7  8  9" + "\n" + "----------------------------");

//Case3:
System.out.print(" 1  2  3  4  5  6  7  8  9" + "\n" + "----------------------------");