`
李灵晖-raylee
  • 浏览: 129713 次
博客专栏
Group-logo
从头认识java
浏览量:0
文章分类
社区版块
存档分类
最新评论

从头认识java-11.3 格式化输出(1)

 
阅读更多

这一章节我们来讨论一下格式化输出,这个话题我们将通过两个章节来展开描述。

在c语言体系里面,用的最多的估计就是printf这个函数:

printf("%d%f",a,b)

上面简单的一句,使用了格式化输出,%d表示输出整形数字,%f浮点数。

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类。


这一章节就到这里,谢谢。

-----------------------------------

目录





分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics