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

How to align output in java

下次还敢
Release: 2024-04-21 01:30:48
Original
1189 people have browsed it

The printf() method is used in Java for aligned output. You can specify the output method through the alignment flag in the format string: %-: left-aligned %: add a positive sign before positive numbers and a negative sign before negative numbers. %: Add a space before positive numbers and no sign before negative numbers%0: Right-justify, pad with zeros

How to align output in java

How to use Java to align output

Aligned output is useful when formatting text to ensure that columns of data line up neatly, improving readability. In Java, you can use the printf() method to achieve aligned output.

Syntax

##printf(String format, Object... args)

    format: a format character String, specifying the output format.
  • args: Parameters to be formatted.

Alignment flags

In the format string, you can use alignment flags to specify the alignment of the output.

  • %: Indicates starting formatting.
  • -: Left aligned.
  • : Add a positive sign before positive numbers and a negative sign before negative numbers.
  • : Add a space before positive numbers and no sign before negative numbers.
  • 0: Right aligned, padded with zeros.

Width and precision

In addition, you can also specify the width and precision of the output.

    Width: Indicates the minimum width of the output field.
  • Precision: Indicates the number of digits to be displayed after the decimal point (for integers, precision is invalid).

Example

The following example shows how to align output using Java:

<code class="java">String name = "John Doe";
int age = 30;

// 左对齐,宽度为 15
System.out.printf("%-15s: %d%n", name, age);

// 右对齐,宽度为 15,用零填充
System.out.printf("%015s: %d%n", name, age);

// 右对齐,宽度为 15,补齐空格
System.out.printf("%15s: %d%n", name, age);

// 左对齐,精度为 2
System.out.printf("%-5.2f%n", 123.456);</code>
Copy after login
Output:

<code>John Doe       : 30
00000John Doe  : 30
       John Doe: 30
123.46</code>
Copy after login

The above is the detailed content of How to align output 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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template