功能:
- 使用Formatter格式化打印购物发票(项目,数量,价格三列。税额,总计)
过程: - Receipt
printTitle,print,printTotal三个方法
个人实现:
package thinking;
import java.util.Formatter;
public class Receipt {
private double total = 0.0;//使用Double
private Formatter formatter = new Formatter(System.out);
private void printTitle() {
formatter.format("%-15s %5s %10s\n", "Item", "Qty", "Price");
formatter.format("%-15s %5s %10s\n", "----", "---", "----");
}
private void print(String item,int qty,double price) {
//formatter.format("%-15s %5d %10f\n", item, qty, price);
formatter.format("%-15.15s\t %5d %10.2f\n", item, qty, price);//注意添加\t,否则汉字显示格式不对
total += price;
}
private void printTotal() {
formatter.format("%-15s %5s %10s\n", "----", "", "----");
formatter.format("%-15s %5s %10.2f\n", "Tax", "", total*0.03);
formatter.format("%-15s %5s %10f\n", "total", "", total*1.03);
}
public static void main(String[] args) {
Receipt receipt = new Receipt();
receipt.printTitle();
receipt.print("土豆", 2, 12.5);
receipt.print("番茄", 4, 25.5);
receipt.print("西瓜", 1, 8.0);
receipt.print("其他其他其他其他其他其他其他其他其他其他其他其他其他", 1, 222.2);
receipt.print("abc", 2, 12.5);
receipt.print("cde", 4, 25.5);
receipt.print("f", 1, 8.0);
receipt.print("hhahahhhahahhhahahhhahahhhahahhhahahhhahahhhahahhhahah", 1, 222.2);
receipt.printTotal();
}
}
比较:
- 注意\t的使用(参考https://blog.csdn.net/yinxbd/article/details/78320924)