第十三章 字符串(二)之格式化输出
格式化输出这一部分的内容非常锁碎,掌握基础就好,用到什么查什么就好了。
Formatter类
1、常规类型、字符类型和数值类型的格式说明符的语法如下:
%[argument_index$][flags][width][.precision]conversion
可选的 argument_index 是一个十进制整数,用于表明参数在参数列表中的位置。第一个参数由 "1$" 引用,第二个参数由 "2$" 引用,依此类推。
可选 flags 是修改输出格式的字符集。有效标志集取决于转换类型。
可选 width 就是域宽。
可选 precision 就精度,用于字符串和数值类型效果不同。
所需 conversion 是一个表明应该如何格式化参数的字符。给定参数的有效转换集取决于参数的数据类型。
转换 | 说明 | 转换 | 说明 |
---|---|---|---|
%d | 十进制整型 | %e | 浮点数科学计数 |
%c | Unicode字符 | %x | 十六进制整数 |
%s | String | %h | 散列码 |
%f | 十进制浮点数 |
2、FormatterAPI用法示例
Formatter解析:Formater封装了一些格式化的的功能,其本质还是向流中写入数据,最常应用的就是PrintStream。
示例:
1 import java.util.Formatter; 2 3 public class Demo3 { 4 5 public static void main(String[] args) { 6 Formatter f = new Formatter(System.out); 7 8 char c = 'c'; 9 System.out.println("c = " + c); 10 f.format("c: %c\n", c); 11 f.format("s: %s\n", c); 12 f.format("b: %b\n", c); 13 14 float x = 3.1415f; 15 System.out.println("x = " + x); 16 f.format("f: %.3f\n", x); 17 18 float y =123.4567f; 19 System.out.println("y = " + y); 20 f.format("e: %e\n", y); 21 22 Demo3 d = new Demo3(); 23 System.out.println("d = " + d); 24 f.format("h: %h\n", d); 25 26 f.close(); 27 } 28 29 }
输出结果:
c = c
c: c
s: c
b: true
x = 3.1415
f: 3.141
y = 123.4567
e: 1.234567e+02
d = stringdemo.Demo3@13a57a3b
h: 13a57a3b
结果说明:这个地方真的没啥想说的,不是是很重要,但是锁碎而细节,用到的时候多查一查把,千万别想当然就好。例如,%b可以转换任何类型的参数,当参数不是boolean型时,只要参数非null,就返回true值。
3、String中的format()方法
public class Test6 { class A { int i = 1; long l = 123456; float f = 3.14f; double d = 3.1415926; public String toString() { return String.format("i = %d l = %d f = %f d = %f", i, l, f, d); } } public static void main(String[] args) { // TODO Auto-generated method stub Test6 t = new Test6(); A a = t.new A(); System.out.println(a); } }
输出结果:
i = 1 l = 123456 f = 3.140000 d = 3.141593
结果说明:String.format()与正常的format()用法一致,只不过返回的是String。