java使用Formatter的时候中英文格式不能对齐
今天看java编程思想的时候,在第13章13.5小节格式化输出的时候遇到一个问题就是格式化内容中有中文的时候不能很好的对齐,于是上网找解决方法在这里发现了解决方法就是通过添加”\t”来实现。
最开始的时候
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("%-15s %5s %10.2f\n", "Tax","",total*0.06);
f.format("%-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("大宝SOD密", 5, 4.25);
receipt.print("Princess Peas", 2, 5.1);
receipt.print("时间简史", 1, 14.29);
receipt.printTotal();
}
}
结果:
然后添加”\t”
public class Receipt {
private double total=0;
private Formatter f=new Formatter(System.out);
public void printTitle(){
f.format("%-15s\t %5s %10s\n", "Item","Qty","Price");
f.format("%-15s\t %5s %10s\n", "----","---","-----");
}
public void print(String name,int qty,double price){
f.format("%-15.15s\t %5d %10.2f\n", name,qty,price);
total+=price;
}
public void printTotal(){
f.format("%-15s\t %5s %10.2f\n", "Tax","",total*0.06);
f.format("%-15s\t %5s %10s\n", "","","-----");
f.format("%-15s\t %5s %10.2f\n", "Total","",total*1.06);
}
public static void main(String[] args) {
Receipt receipt=new Receipt();
receipt.printTitle();
receipt.print("大宝SOD密", 5, 4.25);
receipt.print("Princess Peas", 2, 5.1);
receipt.print("时间简史", 1, 14.29);
receipt.printTotal();
}
}
结果:
java中的\t是一个转义字符,相当于一个制表符tab
但是还是有个问题就是当字符串太长的时候,英文字符能正常显示,而中文字符不能,不知道怎么解决
比如
receipt.print("大宝SOD密dsadasdasdasasddsada", 5, 4.25);
receipt.print("Princess Peasdsadasdasdasdadsa", 2, 5.1);
图: