7. 格式化输出
• JDK5引入了System.out.format或者printf用于格
式化输出, 示例:
int i = 5;
double d = 5.3;
System.out.format(“Row 1: *%d %f+n”, x, y); // 或者
System.out.printf(“Row 1: *%d %f+n”, x, y);
• 示例: demo/Demo2.java
• java.util.Formatter用于格式化字符串, 输出到标
准输出或者附加到某个对象, 比如:
Formatter fmt = new Formatter(System.out);
fmt.format(“Now is %d o’clock”, 5); // 输出到标准输出
StringBuffer buf = new StringBuffer();
Formatter fmt = new Formatter(buf);
fmt.format(“Now is %d o’clock”, 5); // 添加到StringBuffer
System.out.println(buf.toString());
• 示例: demo/Demo3.java
8. 格式化输出
常用的占位符
• 以上一节的” Now is %d o’clock” 为例, 这里的
%d就是一个占位符, 表示相应位置的参数格
式化为一个整数; 常用的占位符有:
d Integral (as decimal)
x Hex
c Unicode character
b Boolean value
s String
• 示例: demo/Demo4.java