Home >Java >javaTutorial >How to align output data in java

How to align output data in java

下次还敢
下次还敢Original
2024-04-21 02:28:00646browse

Tips for aligning output data in Java: Use the printf() method and include format specifiers in the format string. Left-aligned integers (signed) use %-d, right-aligned integers (signed, padded with 0s) use . Use %s to left-justify a string, and s to right-justify a string (padded with spaces).

How to align output data in java

Tips for aligning output data in Java

How to align output data?

In Java, you can align output data by using the printf() method. printf() The method provides a set of format specifiers to control the format and alignment of the output data.

How to use the printf() method to align output data?

printf() The syntax of the method is as follows:

<code class="java">public static Formatter printf(String format, Object... args)</code>

Among them:

  • format: a Format string containing format specifiers.
  • args: Data to be formatted for output.

To align output data, appropriate format specifiers need to be used in the format string. Common alignment format specifiers are:

  • %-d: left-aligned integer (signed)
  • : Right-justified integer (signed, padded with 0s)
  • %s: Left-justified string
  • s: Right-justified String (padded with spaces, width 20)

Example:

<code class="java">int number = 12345;
String name = "John";

System.out.println(String.format("%-10s:%d", "Number", number));
System.out.println(String.format("%10s:%s", "Name", name));</code>

Output:

<code>Number: 12345
       Name: John</code>

at the first printf() In the call, the %-10s format specifier left-aligns "Number" to a width of 10 characters. In the second printf() call, the s format specifier right-aligns "Name" to a width of 10 characters.

The above is the detailed content of How to align output data 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

Related articles

See more