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但仍无法弄明白!!!请帮忙。
答案 0 :(得分:4)
您的格式字符串应为Name:param指定多个字符宽度(%1s
):
System.out.format("%15s%50s%50s", "name = " + i.getName(), "color = " + i.getColor(), "quantity = " + i.getQuantity());
更易读的只是将变量注入格式字符串:
System.out.format("Name: %-10s Color: %-10s Quantity: %-10s Price: %s", ...)
答案 1 :(得分:0)
尝试
String fmt = "Name: %-10s Color: %-10s Quantity: %d%n";
System.out.printf(fmt, "bike", "black", 1);
System.out.printf(fmt, "ladder", "blue", 1);
输出
Name: bike Color: black Quantity: 1
Name: ladder Color: blue Quantity: 1