java - 对齐列

标签 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

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

最佳答案

您可以将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/

相关文章:

c# - 如何避免浪费屏幕空间编写稀疏的 C# 代码?

php: 自动缩进整个代码?

java - 在初始化中加载变量的最佳实践是什么

perl - emacs 中正确的 perl 开关格式

java - 流分组值

ruby - Prawn Tables,Ruby 将制表符添加到字符串

c++ - std::string::assign 是否占用字符串的 "ownership"?

在 R 中使用 gsub 替换以模式开头的整个单词

java - 构建和配置文件标签中的 Maven antrun 插件

java - JDBC——松散耦合