Thinking in Java 13.5.4格式化说明符

功能:

  • 使用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)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值