Home > Java > javaTutorial > body text

How to right align in java

下次还敢
Release: 2024-04-21 02:32:31
Original
622 people have browsed it

There are two ways to right-align text in Java: 1. Use the printf() method and use the "%-10s" specifier in the format string, where 10 represents the output field width; 2. Use String.format() method, also uses the "%-10s" specifier in the format string to right-align the returned format string.

How to right align in java

#How to right align in Java?

There are two main ways to right-align text in Java:

1. Use the printf() method

The printf() method accepts A format string containing %flags[.precision]s specifiers that control the output format. To align right, you can use - flag.

<code class="java">System.out.printf("%-10s", "Right-aligned");</code>
Copy after login

This will output:

<code>Right-aligned</code>
Copy after login

where 10 represents the width of the output field.

2. Use the String.format() method

The String.format() method also accepts a formatted string, but it returns a formatted character string instead of printing it directly to the console. To right-align, you can use the %flags[.precision]s specifier, where the - flag means right-align.

<code class="java">String formatted = String.format("%-10s", "Right-aligned");
System.out.println(formatted);</code>
Copy after login

This will output the same results as above.

The above is the detailed content of How to right align in java. For more information, please follow other related articles on the PHP Chinese website!

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