对齐列
Aligning columns
我需要在列中显示以下字符串的输出:
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
我非常需要字符串的缩进(宽度)。
您可以将您的 item
(s) 和 String
(s) 放入数组中,并使用 %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
我需要在列中显示以下字符串的输出:
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
我非常需要字符串的缩进(宽度)。
您可以将您的 item
(s) 和 String
(s) 放入数组中,并使用 %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