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

How to align output data in java

下次还敢
Release: 2024-04-21 02:28:00
Original
658 people have browsed it

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>
Copy after login

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>
Copy after login

Output:

<code>Number: 12345
       Name: John</code>
Copy after login

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!

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