您好,我想打印一些东西以便它们对齐。
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");
}
输出是
Lily [Animal]
Mary [NPC]
Peter [Animal]
Squash [PC]
我只想让[动物]、[NPC]和[PC]像这样对齐
Lily [Animal]
Mary [NPC]
Peter [Animal]
Squash [PC]
假设我知道没有名称会超过 15 个字符。
最佳答案
我认为您会发现在格式字符串本身中进行所有格式化要容易得多,即
System.out.printf("\t%s [%s]\n", creature.getName(), creature.getCreatureType());
会打印
Lily [Animal]
etc...
可以咨询String formatting documentation关于用于为字符串打印至少 15 个空格以实现对齐效果的确切格式,例如
System.out.printf("\t%15s[%s]\n", creature.getName(), creature.getCreatureType());
关键是为 %15s
中的参数列表中的第一项指定 15 个字符的“宽度”。
关于java - 如何使用 printf() (Java) 正确格式化文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5806886/