格式化输出

1.1 printf()

System.out.printf("Row 3: [%d,%f]\n",x,y);

这段代码运行,首先将x的值插入到%d的位置,然后将y的值插入到%f的位置。这些占位符称作格式修饰符,其不但说明了插入数据的位置,同时还说明了将插入什么类型的变量。

1.2 System.out.format()

format()和printf()是等价的。

public class SimpleFormat {

    public static void main(String[] args) {
        int x = 3;
        double y = 3.141592;
        System.out.println("Row 1: [" + x + "," + y + "]");
        System.out.format("Row 2: [%d,%f]\n", x, y);
        System.out.printf("Row 3: [%d,%f]\n",x,y);
    }
}

运行结果:

Row 1: [3,3.141592]
Row 2: [3,3.141592]
Row 3: [3,3.141592]

1.3 Formatter类

在Java中,所有新的格式化功能都由java.util.Formatter类处理。

public class Tom {
    private String name;

    private Formatter f;

    public Tom(String name, Formatter f) {
        this.name = name;
        this.f = f;
    }

    public void move(int x, int y) {
        f.format("%s And Tom is at (%d,%d)\n", name, x, y);
    }

    public static void main(String[] args) {
        PrintStream out = System.out;
        Tom jerry = new Tom("Jerry",new Formatter(System.out));
        Tom spike = new Tom("Spike",new Formatter(out));
        jerry.move(0,0);
        spike.move(1,1);
        jerry.move(1,2);
        spike.move(2,1);
    }
}

运行结果:

Jerry And Tom is at (0,0)
Spike And Tom is at (1,1)
Jerry And Tom is at (1,2)
Spike And Tom is at (2,1)

所有的jerry输出到System.out,而所有的spike都输出到System.out的一个别名中

1.4 格式化说明符

在默认情况下,数据是右对齐,可以通过使用"-"标志来改变对齐方向。通过 .precision 来控制小数部分的显示位数(默认情况下是6位小数),如果位数过多就舍入,过少则位数补0,无法用于整数。

public class Receipt {
    private double total = 0;
    private Formatter f = new Formatter(System.out);

    public void printTitle() {
        f.format("%-10s %5s %10s\n", "Item", "Qty", "Price");
        f.format("%-10s %5s %10s\n", "----", "----", "----");
    }

    public void print(String name, int qty, double price) {
        f.format("%-10s %5d %10.2f\n", name, qty, price);
        total += price;
    }

    public void printTotal(){
        f.format("%-10s %5s %10s\n", "", "", "----");
        f.format("%-10s %5s %10.2f\n", "total", "", total);
    }

    public static void main(String[] args) {
        Receipt r = new Receipt();
        r.printTitle();
        r.print("Beans",1,2.13);
        r.print("Apple",2,3.24);
        r.printTotal();
    }
}

输出结果:

Item         Qty      Price
----        ----       ----
Beans          1       2.13
Apple          2       3.24
                       ----
total                  5.37

1.5 Formatter转换

类型转换字符

d 整数型(十进制)
c Unicode字符
b Boolean值
s String
f 浮点数(十进制)
e 浮点数(科学计数)
x 整数(十六进制)
h 散列码(十六进制)
% 字符"%"

1.6 String.format()

生成格式化的String对象。

public class StringFormat {

    private String format(String name,int x,int y){
        return String.format("%s is at (%d,%d)",name,x,y);
    }

    public static void main(String[] args) {
        StringFormat sf = new StringFormat();
        System.out.println(sf.format("Tom",1,4));
    }
}

输出结果:

Tom is at (1,4)

你可能感兴趣的:(格式化输出)