Methods to achieve text alignment in Java include: using the String.format() method to specify the alignment, text width and type; using the DecimalFormat class to format and align numbers; using StringBuilder to dynamically splice text and Control alignment.
Quickly align text in Java
Method 1: String.format()
Use the String.format()
method to quickly align text. The format is as follows:
<code class="java">String.format("%<flags><width>.<precision>[type]string", object)</code>
where:
(left-aligned) or
(right-aligned)
: Specify Minimum width of text
Method 2: DecimalFormat
For numbers, you can useDecimalFormat Class to format and align text.
Example:
<code class="java">DecimalFormat df = new DecimalFormat("#,###.##"); String s = df.format(123456.789); System.out.println(s); // 输出:123,456.79 (右对齐,小数点后保留两位)</code>
Method 3: StringBuilder
For situations where dynamic splicing of text is required, you can use StringBuilder.
Example:
<code class="java">StringBuilder sb = new StringBuilder(); sb.append("Hello").append(" ").append("World"); String s = sb.toString(); System.out.println(s); // 输出:Hello World</code>
The above is the detailed content of How to quickly align in java. For more information, please follow other related articles on the PHP Chinese website!