使用Formatter在Java中垂直对齐数值
要在Java中垂直对齐数值,请使用Formatter。要使用Formatter类,请导入以下软件包。
import java.util.Formatter;
取一个数组-
double arr[] = { 2.5, 4.8, 5.7, 6.5, 9.4, 8.4, 9.5, 10.2, 11.5 };显示此双精度数组值时,请使用%f设置空格-
for (double d : arr) {
f.format("%12.2f %12.2f %12.2f\n", d, Math.ceil(d), Math.floor(d));
}上面,我们还设置了小数位,即12.2f表示2个小数位。
以下是一个例子-
示例
import java.util.Formatter;
public class Demo {
public static void main(String[] argv) throws Exception {
double arr[] = { 2.5, 4.8, 5.7, 6.5, 9.4, 8.4, 9.5, 10.2, 11.5 };
Formatter f = new Formatter();
f.format("%12s %12s %12s\n", "Points1", "Points2", "Points3");
System.out.println("The point list...\n");
for (double d : arr) {
f.format("%12.2f %12.2f %12.2f\n", d, Math.ceil(d), Math.floor(d));
}
System.out.println(f);
}
}输出结果
The point list... Points1 Points2 Points3 2.50 3.00 2.00 4.80 5.00 4.00 5.70 6.00 5.00 6.50 7.00 6.00 9.40 10.00 9.00 8.40 9.00 8.00 9.50 10.00 9.00 10.20 11.00 10.00 11.50 12.00 11.00
热门推荐
10 年底老板祝福语简短的
11 送给姐姐简短的祝福语
12 哥哥中考加油祝福语简短
13 写字生日祝福语简短独特
14 写生日祝福语简短唯美
15 姨父生日祝福语简短精辟
16 高考给舍友祝福语简短
17 新婚抖音祝福语简短
18 迟到的过年祝福语简短