In Java, the printf() method is used to align output. The steps are as follows: Specify the format specifier, such as %d for an integer. Alignment is specified using alignment flags: '-' left-justified, ' ' a plus sign before positive numbers, ' ' a space before positive numbers, '0' right-justified and padded with zeros. Set minimum field width, specify the minimum width of the output field. Based on these parameters, use the printf() method to align the output.
How to align output in Java
In Java, you can use printf()
method to align the output. This method requires the following parameters:
%d
represents an integer, %f
represents a floating point number. Alignment flag
The alignment flag can be the following values:
-
: left Alignment
: Display a positive sign before a positive number
: Display a space before a positive number 0
: Right justified and padded with zeros Minimum field width
Minimum field width specifies the minimum width of the output field. If the length of the output text is less than the minimum width, padding characters are used to pad the output fields.
Example
The following example outputs the floating point number 5.5
right-justified, with a minimum field width of 10, padded with spaces:
<code class="java">System.out.printf("%10.2f", 5.5);</code>
Output:
<code> 5.50</code>
The following example outputs the integer 123
left justified, with a minimum field width of 6, and zero padding:
<code class="java">System.out.printf("%-6d", 123);</code>
Output:
<code>123 </code>
The following example outputs the string "Hello" as center-aligned, with a minimum field width of 10, and padding with asterisks:
<code class="java">System.out.printf("%10s", "Hello");</code>
Output:
<code> Hello </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!