标签:java编程思想
/** * 书本:《Thinking In Java》 * 功能:对于java字符串格式化说明符 * format字符串的格式化参数语法如下: * %[argument_index$][flags][width][.precision]conversion * 文件:Receipt.java * 时间:2015年4月11日19:40:53 * 作者:cutter_point */ package Lesson13_strings; import java.util.Formatter; public class Receipt { private double total = 0; private Formatter f = new Formatter(System.out); //指定输出的目的地 public void printTitle() //输出标题 { //这个格式第一个%-15s 是说宽度为15的字符串,后面类同,只是-还是不太清楚是个什么 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("%-15.15s %5s %10.2f\n", "Tax", "", total*0.06); f.format("%-15s %5s %10s\n", "", "", "------"); f.format("%-15.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); receipt.printTotal(); Formatter ff = new Formatter(System.out); ff.format("%5d", 998); } }
输出:
Item Qty Price
---- --- -----
Jack‘s Magic Be 4 4.25
Princess Peas 3 5.10
Three Bears Por 1 14.29
Tax 1.42
------
Total 25.06
998
【ThinkingInJava】26、java字符串格式化说明符
标签:java编程思想
原文地址:http://blog.csdn.net/cutter_point/article/details/45507597