JAVA中的Formatter

package com.st.day20150525;

import java.util.Formatter;

public class StringTest02 {
    /**
     *    %[argument_index$][flags][width][.precision]conversion
     *    具体的参数解释,可以查看对应的API
     */
    private static double total = 0 ;
    private static Formatter formatter = new Formatter(System.out); 
    public static void printTitle(){
        formatter.format("%-15s %-5s %-10s\n", "Item","Qty","Price");
        formatter.format("%-15s %-5s %-10s\n", "-----","---","----");
    }
    
    public static void print(String name,int qty,double price){
        formatter.format("%-15s %-5d %-10.2f\n", name,qty,price);
        total += price ;
    }
    
    public static void printTotal(){
        formatter.format("%-15s %-5s %-10.2f\n", "Tex","",total*0.6);
        formatter.format("%-15s %-5s %-10s\n", "","","-----");
        formatter.format("%-15s %-5s %-10.2f\n", "Total","",total*1.6);
    }
    public static void main(String[] args) {
        printTitle();
        print("apple", 3, 2.5);
        print("orange", 1, 1.2);
        print("banana", 10, 0.5);
        printTotal();
        
        //任何类型都可以b(布尔类型)进行转换,只有为null的时候返回false
        formatter.format("%b\n", 0);
        formatter.format("%b\n", "");
        formatter.format("%b\n", null);
        // 如果只是简单的字符串格式化,可以使用String.format 
        // 其内部实现new Formmatter对象
        System.out.println(String.format("%-15s %-5s %-10s", "我可以","做","一样的事情"));
        
    }
}

 

posted @ 2015-07-07 22:59  专注、坚持  阅读(1965)  评论(0编辑  收藏  举报