1
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,但仍然无法弄清楚!请帮忙。

4

2 回答 2

4

%1s您的格式字符串应为 Name: 参数指定多个字符宽度 ( ):

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", ...)
于 2012-12-13T00:05:28.710 回答
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
于 2012-12-13T00:41:50.423 回答