gpt4 book ai didi

java - 努力正确格式化字符串

转载 作者:行者123 更新时间:2023-11-29 03:39:25 25 4
gpt4 key购买 nike

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com