JAVA编程思想 13.5.4 java 字符串> 格式化字符> 购物收据

import  java.util.Formatter;
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(
" %-15.15s   %5s   %10.2f\n " " Tax " , "" ,total * 0.06 );
     f.format(
" %-15.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 );
         receipt.printTotal();
    }
    
    
/*
    %[argument_index$][flag][width][.precision]conversion
    在默认的情况下,数据是右对齐,通过“-”标志来改变对齐方向
    width可以用于各种类型的数据转换
    precision不是所有类型的数据都能使用precision,用于不同数据时的意义不同。
         1.应用于String时,它表示打印String时输出字符的最大数量。
         2.应用于浮点数时,它表示小数部分显示出来的位数(默认是6位小数),如果小数位数过多四舍五入,太少尾部补零。
         3.应用于整数时,由于整数没有小数部分,则会触发异常。
    
     
*/
    
}


  类型转换字符
d 整数类型
e 浮点数(科学计数)
c Unicode字符
x 整数(十六进制)
b Boolean值
h 散列码(十六进制)
s String % 字符%
f 浮点数(十进制)     
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值