gpt4 book ai didi

java - 对齐列

转载 作者:行者123 更新时间:2023-12-02 03:23:31 25 4
gpt4 key购买 nike

我需要将以下字符串的输出显示在列中:

 System.out.printf("Weight of Item 1: %10d%n", ITEM_1);
System.out.printf("Weight of Item 2: %10d%n", ITEM_2);
System.out.printf("Weight of Item 3: %10d%n", ITEM_3);
System.out.printf("Total Weight Kilograms: %10d%n", totalWeightKilograms);

我可以将输入到字符串中的变量转移到我想要的位置。我无法获取变量之前的文本格式。基本上,我得到的输出:

Weight of Item 1:         38
Weight of Item 2: 23
Weight of Item 3: 12
Total Weight Pounds: 73

我想要的是:

   Weight of Item 1:         38
Weight of Item 2: 23
Weight of Item 3: 12
Total Weight Pounds: 73

我需要字符串的缩进(宽度),因为我需要它。

最佳答案

您可以将itemString放入数组中,并使用%s指定格式长度> 只要最长的 String(22 个字符)即可。类似这样的东西,

String[] msg = { "Weight of Item 1", "Weight of Item 2", "Weight of Item 3",
"Total Weight Kilograms" };
int[] items = { ITEM_1, ITEM_2, ITEM_3, totalWeightKilograms };
for (int i = 0; i < msg.length; i++) {
System.out.printf("%22s: %10d%n", msg[i], items[i]);
}

哪个输出(根据要求)

      Weight of Item 1:         38
Weight of Item 2: 23
Weight of Item 3: 12
Total Weight Kilograms: 73

关于java - 对齐列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39312589/

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