for(Item i : itemArray){
System.out.format("%1s%50s%50s", "name = " + i.getName(), "color = " + i.getColor(), "quantity = " + i.getQuantity());
System.out.println();
我正在尝试遍历项目数组,打印出格式化表格中的每个项目。 每件商品都有名称、颜色、数量和价格。
这是目前的结果:
Name: bike Color: black Quantity: 1 Price: 6.00
Name: ladder Color: blue Quantity: 150 Price: 9.00
Name: dolphin Color: orange Quantity: 15 Price: 100000.00
Name: key Color: red Quantity: 12 Price: 510.00
这是我需要的样子:
Name: bike Color: black Quantity: 1 Price: 6.00
Name: ladder Color: blue Quantity: 150 Price: 9.00
Name: dolphin Color: orange Quantity: 15 Price: 100000.00
Name: key Color: red Quantity: 12 Price: 510.00
格式api我都看了,还是搞不懂!!!请帮忙。
最佳答案
您的格式字符串应为名称指定多个字符宽度 (%1s
): 参数:
System.out.format("%15s%50s%50s", "name = " + i.getName(), "color = " + i.getColor(), "quantity = " + i.getQuantity());
更具可读性的是只将变量注入(inject)格式字符串:
System.out.format("Name: %-10s Color: %-10s Quantity: %-10s Price: %s", ...)
关于java - 努力正确格式化字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13850795/