如何使用printf()正确格式化文本(Java)

Kir*_*gle 3 java printf

您好,我想打印一些东西,以便它们对齐。

    for (int i = 0; i < temp.size(); i++) {
        //creatureT += "[" + temp.get(i).getCreatureType() + "]";
        creatureS = "\t" + temp.get(i).getName();
        creatureT = " [" + temp.get(i).getCreatureType() + "]";
        System.out.printf(creatureS + "%15a",creatureT + "\n");
   }
Run Code Online (Sandbox Code Playgroud)

输出是

    Lily      [Animal]
    Mary         [NPC]
    Peter      [Animal]
    Squash          [PC]
Run Code Online (Sandbox Code Playgroud)

我只希望[Animal],[NPC]和[PC]像

    Lily      [Animal]
    Mary      [NPC]
    Peter     [Animal]
    Squash    [PC]
Run Code Online (Sandbox Code Playgroud)

说我知道没有名字会超过15个字符。

mat*_*t b 5

我认为您会发现在格式字符串本身中进行所有格式设置要容易得多,即

System.out.printf("\t%s [%s]\n", creature.getName(), creature.getCreatureType());
Run Code Online (Sandbox Code Playgroud)

将打印

  Lily [Animal]
  etc...
Run Code Online (Sandbox Code Playgroud)

您可以查询有关确切格式的字符串格式文档,以使用至少为字符串打印15个空格来获得对齐效果,例如

System.out.printf("\t%15s[%s]\n", creature.getName(), creature.getCreatureType());
Run Code Online (Sandbox Code Playgroud)

关键是要为参数列表中的第一项指定15个字符的“宽度” %15s