Formatted printing in Java

 ̄綄美尐妖づ 提交于 2019-12-05 09:42:44

You could use String.format(), which will accept widths.

I think you could change:

String s = day.getDayName() + "    " + day.toString();

to:

return String.format("%9s %s", day.getDayName(), day.toString());

And get what you want.

polygenelubricants

This is the job for java.util.Formatter

    String[][] kvs = {
            { "Name", "Johnny" },
            { "Age", "19" },
            { "Sex", "Female" },
    };
    for (String[] kv : kvs) {
        System.out.println(
            String.format("%-10s:%10s", kv[0], kv[1])
        );
    }

This prints:

Name      :    Johnny
Age       :        19
Sex       :    Female

Syntax

%[flags][width]conversion
  • - is the flag for left justification
  • s is the String conversion

On String concatenation

Note that you should never build a String using += in a loop. You should use a StringBuilder instead.

StringBuilder sb = new StringBuilder();
for (Slot slot: slots) {
    sb.append(slot.toString());
}
return sb.toString();

Related questions

Have you checked out java.util.Formatter? It's available from 1.5 btw.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!