我正在尝试显示左对齐的百分号以及其他整数和字符串的数字。为此,我在java中使用字符串格式。我几乎得到它但是当十位移动到一百位时卡住了。例如:
public class Test1 {
public static void main(String args[]){
int per1= 100,g1=3;
String name1="AAA PPPP";
int per2= 55,g2=4;
String name2="BBB QQQ";
int per3= 24,g3=7;
String name3="CCC RRRRR";
System.out.println(String.format("%-3d%% | %02d strike | %s",per1,g1,name1));
System.out.println(String.format("%-3d%% | %02d strike | %s",per2,g2,name2));
System.out.println(String.format("%-3d%% | %02d strike | %s",per3,g3,name3));
}
}
目前,我得到的输出是
100% | 03 strike | AAA PPPP
55 % | 04 strike | BBB QQQ
24 % | 07 strike | CCC RRRRR
但预计是
100% | 03 strike | AAA PPPP
55% | 04 strike | BBB QQQ
24% | 07 strike | CCC RRRRR
我现在严重陷入困境。我知道它非常棘手但仍然很难得到答案。请帮助别人。
答案 0 :(得分:0)
这可能是一种矫枉过正但它有效:
public class Test1 {
public static void main(String args[]){
int per1= 100, g1=3;
String name1="AAA PPPP";
int per2= 55, g2=4;
String name2="BBB QQQ";
int per3= 24, g3=7;
String name3="CCC RRRRR";
String space = "";
System.out.println(String.format("%d%%%-" + (4 - String.valueOf(per1).length()) + "s| %02d strike | %s", per1, space, g1, name1));
System.out.println(String.format("%d%%%-" + (4 - String.valueOf(per2).length()) + "s| %02d strike | %s", per2, space, g2, name2));
System.out.println(String.format("%d%%%-" + (4 - String.valueOf(per3).length()) + "s| %02d strike | %s", per3, space, g3, name3));
}
}
输出:
100% | 03 strike | AAA PPPP
55% | 04 strike | BBB QQQ
24% | 07 strike | CCC RRRRR