Java 正在努力正确格式化字符串

Java 正在努力正确格式化字符串,java,string,api,format,Java,String,Api,Format,我试图迭代一个项目数组,在一个格式化的表中打印出每个项目。 每件商品都有名称、颜色、数量和价格 以下是目前的情况: for(Item i : itemArray){ System.out.format("%1s%50s%50s", "name = " + i.getName(), "color = " + i.getColor(), "quantity = " + i.getQuantity()); System.out.println(); 以下是我需要它的外观: Name: bike

我试图迭代一个项目数组,在一个格式化的表中打印出每个项目。 每件商品都有名称、颜色、数量和价格

以下是目前的情况:

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

我已经读过api的格式,但仍然无法理解!!!请提供帮助。

格式字符串应为名称:param:

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
更具可读性的方法是只将变量注入格式字符串:

System.out.format("%15s%50s%50s", "name = " + i.getName(), "color = " + i.getColor(), "quantity = " + i.getQuantity());

格式字符串应为名称指定多个字符的宽度%1s:param:

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
更具可读性的方法是只将变量注入格式字符串:

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", ...)
输出

        String fmt = "Name: %-10s Color: %-10s Quantity: %d%n";
        System.out.printf(fmt, "bike", "black", 1);
        System.out.printf(fmt, "ladder", "blue", 1);
尝试

System.out.format("Name: %-10s  Color: %-10s Quantity: %-10s Price: %s", ...)
输出

        String fmt = "Name: %-10s Color: %-10s Quantity: %d%n";
        System.out.printf(fmt, "bike", "black", 1);
        System.out.printf(fmt, "ladder", "blue", 1);