从头认识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类。


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

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

目录





  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值