您的位置:首页 > 编程语言 > Java开发

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

2015-12-01 16:38 666 查看
接着上一章节的内容,这一章节主要讲述格式化说明符以及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的类型转换。

这一章节就到这里,谢谢。
-----------------------------------
目录
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  java