这一章节我们来讨论一下格式化输出,这个话题我们将通过几个章节来展开描述。
在c语言体系里面,用的最多的估计就是printf这个函数:
printf("%d%f",a,b)
1.System.out.printf和System.out.format
java继承c语言体系,当然也会有printf之类的函数,我们下面举例:
package com.ray.ch11; public class Test { public static void main(String[] args) { int a = 1; String b = "b"; System.out.printf("%d%s", a, b); System.out.println(); System.out.format("%d%s", a, b); } }
1b
1b
在上面的代码里面System.out.printf和System.out.format是等价的。
2.Formatter类
package com.ray.ch11; import java.util.Formatter; public class Test { private Formatter formatter = new Formatter(System.out);// 这里需要定义输出的地方 public void print(int a, String b) { formatter.format("%d%s", a, b); } public static void main(String[] args) { int a = 1; String b = "b"; new Test().print(a, b); } }
输出:
1b
在使用Formatter类的时候需要注意,它需要定义输出的地方,不然虽然字符串的输出已经存在内存,但是没有输出的地方。我们上面是输出在控制台上面,因此把System.out放到里面去。总结:这一章节我们简单讲述了格式化输出的两个方面,一个是最简单的printf函数,还有一个是Formmater类。
这一章节就到这里,谢谢。
-----------------------------------
原文:http://blog.csdn.net/raylee2007/article/details/50130287