列对齐

时间:2016-09-04 00:44:17

标签: java string indentation

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

 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

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

1 个答案:

答案 0 :(得分:2)

您可以将itemString(s)放入数组,并指定格式长度%s,只要您的String {{1} (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