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 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)
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.
: Right aligned, padded with zeros.
Width and precision
In addition, you can also specify the width and precision of the output.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>
<code>John Doe : 30 00000John Doe : 30 John Doe: 30 123.46</code>
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!