Home >Java >javaTutorial >How to make the output result display in new line in java

How to make the output result display in new line in java

下次还敢
下次还敢Original
2024-04-26 22:39:13428browse

In Java, you can use the following method to wrap the output: '\n' escape character System.lineSeparator()printf()PrintWriter.format()

How to make the output result display in new line in java

How to make the output results in Java wrap to another line?

In Java, there are the following methods to display the output results in new lines:

1. Use the '\n' escape character

The simplest way is to add the '\n' escape character where you want to break the line.

<code>System.out.println("第一行\n第二行");</code>

2. Use System.lineSeparator()

System.lineSeparator() method to return the newline character of the current system platform.

<code>System.out.println("第一行" + System.lineSeparator() + "第二行");</code>

3. Use the printf() method

The printf() method can accept a format string that contains the newline escape sequence "%n".

<code>System.out.printf("第一行%n第二行");</code>

4. Use PrintWriter

The PrintWriter class provides an advanced writing mechanism, which provides the newline() method to wrap lines.

<code>PrintWriter writer = new PrintWriter("output.txt");
writer.println("第一行");
writer.println("第二行");
writer.close();</code>

5. Use the .format() method

The format() method is also a method of formatting the output string, which can contain newlines.

<code>String str = String.format("第一行%n第二行");
System.out.println(str);</code>

Which method to choose depends on the specific scenario and preference. The '\n' escape character and the System.lineSeparator() method are simple and commonly used choices.

The above is the detailed content of How to make the output result display in new line in java. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn