Home > Java > Java Tutorial > body text

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

下次还敢
Release: 2024-04-26 22:39:13
Original
159 people have browsed it

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.

System.out.println("第一行\n第二行");
Copy after login

2. Use System.lineSeparator()

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

System.out.println("第一行" + System.lineSeparator() + "第二行");
Copy after login

3. Use the printf() method

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

System.out.printf("第一行%n第二行");
Copy after login

4. Use PrintWriter

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

PrintWriter writer = new PrintWriter("output.txt");
writer.println("第一行");
writer.println("第二行");
writer.close();
Copy after login

5. Use the .format() method

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

String str = String.format("第一行%n第二行");
System.out.println(str);
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!