作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我需要将以下字符串的输出显示在列中:
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
和String
放入数组中,并使用%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/
我是一名优秀的程序员,十分优秀!