在java中格式化字符串以使其完全匹配
所以我想知道是否有人能帮我格式化这个 以下是它当前的样子: 这就是我需要它的样子(没有…): 这是我目前的代码:在java中格式化字符串以使其完全匹配,java,string,formatting,Java,String,Formatting,所以我想知道是否有人能帮我格式化这个 以下是它当前的样子: 这就是我需要它的样子(没有…): 这是我目前的代码: System.out.format( "%n$------------------------------------$"); System.out.format( "%nWITHHOLDING FOR EACH EMPLOYEE%n%n" ); System.out.format( "First Name Last Name
System.out.format( "%n$------------------------------------$");
System.out.format( "%nWITHHOLDING FOR EACH EMPLOYEE%n%n" );
System.out.format( "First Name Last Name Hourly Rate Weekly Pay Withholding Amount%n%n" );
for( int i = 0; i < employeeNum; i++ ) {
System.out.format( "%-10s %-10s %-10.3f %-10.3f %-10.3f%n", employeeFirstName[i], employeeLastName[i],
employeeHourlyPay[i], weeklyPay[i], withholdingAmt[i] );
}
System.out.format( "%nEND OF REPORT%n" );
System.out.format( "$------------------------------------$");
System.out.format(“%n$-----------------------------------------$”;
System.out.format(“%n为每个员工保留%n%n”);
System.out.格式(“名字姓氏时薪周薪预扣金额%n%n”);
for(int i=0;i
谢谢你的帮助 使用此选项截断长字符串:
static String truncto( String s, int max ){
return s.length() > max ? s.substring(0,max) : s;
}
您可以使用它来获得对齐的输出
System.out.format( "First Name Last Name Hourly Rate Weekly Pay Withholding Amount%n%n" );
System.out.format( "%-17s %-16s %-18.3f %-17.0f %-17.0f%n",
truncto("John-Bulwer-Lytton",17),
truncto("Smith",16),
123.45, 200.0, 100.0 );
使用数组元素代替我用于测试的文本
您当然可以为页眉打印两行。我已经完成了,只需在页眉中使用对齐:
System.out.print( "%n$------------------------------------$");
System.out.printf( "%nWITHHOLDING FOR EACH EMPLOYEE%n%n" );
System.out.printf("%-12s %-12s %-12s %-12s %-12s \n\n", "First Name", "Last Name", "Hourly Rate", "Weekly Pay", "Withholding Amount");
for( int i = 0; i < employeeNum; i++ ) {
System.out.printf( "%-12s %-12s %-12.3f %-12.3f %-12.3f \n", employeeFirstName[i], employeeLastName[i],
employeeHourlyPay[i], weeklyPay[i], withholdingAmt[i] );
}
System.out.printf( "%nEND OF REPORT%n" );
System.out.print( "$------------------------------------$");
为什么不增加“%-10”中的“10”直到对齐???省略不需要小数的.3?你应该看看能帮你做到这一点的库。这里有一个这样的例子:是的,我想没有真正的解决办法,因为字符串可以有不同的大小。我已经限制了名字和姓氏的大小,但它可能仍然不起作用。谢谢你和我确认这一点!
...
First Name Last Name Hourly Rate Weekly Pay Withholding Amount
Brett Lawless 25.500 1020.000 204.000
....