如何使用printf()正确格式化文本(Java) [英] How to format text correctly using printf() (Java)

查看:46
本文介绍了如何使用printf()正确格式化文本(Java)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Hello I want to print something so they are aligned.

    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]对齐

I just want the [Animal], [NPC], and [PC] to be aligned like

    Lily      [Animal]
    Mary      [NPC]
    Peter     [Animal]
    Squash    [PC]

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

Say I know that no name will be greater then 15 characters.

推荐答案

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

I think you'll find it's a lot easier to do all of the formatting in the format string itself, i.e.

System.out.printf("\t%s [%s]\n", creature.getName(), creature.getCreatureType());

将打印

  Lily [Animal]
  etc...

您可以查阅字符串格式说明文件,该格式用于打印至少15个空格以实现对齐效果的字符串,例如

You can consult the String formatting documentation on the exact format to use to print a minimum of 15 spaces for a string to achieve the alignment effect, something like

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

键为%15s 中的参数列表中的第一项指定15个字符的宽度".

The key is specifying a "width" of 15 chars for the first item in the argument list in %15s.

这篇关于如何使用printf()正确格式化文本(Java)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆