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

接着上一章节的内容,这一章节主要讲述格式化说明符以及Formatter的类型转换。

1.格式化说明符

%[argument_index$][flags][width][.precision]conversion 
可选的 argument_index 是一个十进制整数,用于表明参数在参数列表中的位置。第一个参数由 "1$" 引用,第二个参数由 "2$" 引用,依此类推。 

可选的 flags 是修改输出格式的字符集。有效标志的集合取决于转换类型。

可选 width 是一个非负十进制整数,表明要向输出中写入的最少字符数。 

可选 precision 是一个非负十进制整数,通常用来限制字符数。特定行为取决于转换类型。

所需的 conversion 是一个表明应该如何格式化参数的字符。给定参数的有效转换集合取决于参数的数据类型。 

例子:

package com.ray.ch11;

import java.util.Formatter;

public class Test {
	private Formatter formatter = new Formatter(System.out);// 这里需要定义输出的地方
	private double total = 0;

	public void showTitle() {
		formatter.format("%-15s %5s %10s\n", "Item", "Qty", "Price");
		formatter.format("%-15s %5s %10s\n", "----", "---", "-----");
	}

	public void showContent(String item, int qty, double price) {
		formatter.format("%-15.15s %5d %10.2f\n", item, qty, price);
		total += price;
	}

	public void showTotal() {
		formatter.format("%-15s %5s %10.2f\n", "Tax", "", total * 0.17);
		formatter.format("%-15s %5s %10s\n", "----", "---", "-----");
		formatter.format("%-15s %5s %10.2f\n", "Total", "", total * 1.17);
	}

	public static void main(String[] args) {
		Test test = new Test();
		test.showTitle();
		test.showContent("aaaaaaaaa", 1, 1.3);
		test.showContent("bbbbbb", 2, 3.3);
		test.showContent("ttttttttttt", 4, 7.2);
		test.showTotal();
	}
}

输出:

Item              Qty      Price
----              ---      -----
aaaaaaaaa           1       1.30
bbbbbb              2       3.30
ttttttttttt         4       7.20
Tax                         2.01
----              ---      -----
Total                      13.81


粘贴过来的输出有些问题,请大家手动运行一下代码,使用格式化输出,对空格与对齐具有强大的支持。


2.Formatter的类型转换

package com.ray.ch11;

import java.util.Formatter;

public class Test {
	private Formatter formatter = new Formatter(System.out);// 这里需要定义输出的地方

	public void show() {
		char a = 'a';
		formatter.format("%c\n", a);
		formatter.format("%s\n", a);
		formatter.format("%b\n", a);
		//formatter.format("%d\n", a);// error
		//formatter.format("%f\n", a);// error
		//formatter.format("%h\n", a);// error
	}

	public static void main(String[] args) {
		Test test = new Test();
		test.show();
	}
}

输出:

a
a
true


从上面的代码可以看出,使用Formatter可以改变原来的类型,当然,这个必须是在java能够转换的前提下,就像上面注释的那些代码,如果运行起来,将会抛异常。


总结:这一章节主要讲述格式化说明符以及Formatter的类型转换。


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

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

目录



  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值