C语言中我们常常用printf()风格的格式化输出一些内容,Java推出类似Formatter类来控制输出格式,其格式语法%[argument_index$][flags][width][.precision]conversion(%参数索引,控制对齐符号,宽度,精确度,内容类型,但如果内容是String的话,precision代表的是最大字符长度)
运行结果:
public class Receipt {
private double total = 0;
private Formatter f = new Formatter(System.out);
public void printTitle() {
f.format("%-15s %5s %10s\n", "Item", "Qty", "Price");
f.format("%-15s %5s %10s\n", "----", "---", "-----");
}
public void print(String name, int qty, double price) {
f.format("%-15.15s %5d %10.2f\n", name, qty, price);
total += price;
}
public void printTotal() {
f.format("%-15s %5s %10.2f\n", "Tax", "", total*0.06);
f.format("%-15s %5s %10s\n", "", "", "-----");
f.format("%-15s %5s %10.2f\n", "Total", "",
total * 1.06);
}
public static void main(String[] args) {
Receipt receipt = new Receipt();
receipt.printTitle();
receipt.print("Jack's Magic Beans", 4, 4.25);
receipt.print("Princess Peas", 3, 5.1);
receipt.print("Three Bears Porridge", 1, 14.29);
//可以直接调用String.format静态方法直接格式化输出内容
System.out.println(String.format("%-15s %5s %10s","beyondboy","scau","sungirl"));
receipt.printTotal();
}
}
运行结果:
Item Qty Price
—- — —–
Jack’s Magic Be 4 4.25
Princess Peas 3 5.10
Three Bears Por 1 14.29
beyondboy scau sungirl
Tax 1.42
—–
Total 25.06