Java中的格式化打印

时间:2010-05-13 08:22:58

标签: java printing formatted

我有这段代码:

public String toString(Day day)
{
    String s = day.getDayName() + "    " + day.toString();
    return s;
}

这是Day类的toString方法:

public String toString()
{
    String s = "";
    for (Slot slot: slots)
        s += slot.toString();
    return s;
}

一遍又一遍地打电话打印:

barbi
 monday    10: X 11:   12:   2:   3:   4:
 tuesday    10:   11:   12:   2:   3:   4: X
 wednesday    10:   11:   12:   2:   3:   4:
 thursday    10:   11:   12:   2:   3:   4:
 friday    10:   11:   12:   2:   3:   4:
    bobbi
 monday    10:   11:   12:   2:   3:   4:
 tuesday    10:   11:   12:   2:   3:   4:
 wednesday    10:   11:   12:   2:   3:   4:
 thursday    10:   11:   12:   2: X 3:   4:
 friday    10:   11:   12:   2:   3:   4:
    bunny
 monday    10:   11:   12:   2:   3:   4:
 tuesday    10:   11:   12:   2:   3:   4:
 wednesday    10:   11:   12:   2:   3:   4:
 thursday    10:   11:   12:   2:   3:   4:
 friday    10:   11:   12:   2:   3:   4:

但是,我想以这种方式打印:

barbi, income is $95.00
Monday    10:   11:   12: X 2:   3:   4:
Tuesday   10:   11:   12:   2:   3:   4:
Wednesday 10:   11:   12:   2:   3:   4:
Thursday  10:   11:   12:   2:   3:   4:
Friday    10:   11:   12:   2:   3:   4:
bobbi, income is $45.00
Monday    10:   11:   12:   2:   3:   4:
Tuesday   10:   11:   12:   2:   3: X 4:
Wednesday 10:   11:   12:   2:   3:   4:
Thursday  10:   11:   12:   2:   3:   4:
Friday    10:   11:   12:   2:   3:   4:
bunny, income is $0.00
Monday    10:   11:   12:   2:   3:   4:
Tuesday   10:   11:   12:   2:   3:   4:
Wednesday 10:   11:   12:   2:   3:   4:
Thursday  10:   11:   12:   2:   3:   4:
Friday    10:   11:   12:   2:   3:   4:

我知道这适用于Java中的格式化打印。但我不知道该怎么做。

3 个答案:

答案 0 :(得分:5)

您可以使用String.format(),这将接受宽度。

我认为你可以改变:

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

为:

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

得到你想要的东西。

答案 1 :(得分:3)

这是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])
        );
    }

打印:

Name      :    Johnny
Age       :        19
Sex       :    Female

语法

%[flags][width]conversion
  • -是左对齐的标志
  • sString转化

String连接

请注意,您绝不应在循环中使用String构建+=。您应该使用StringBuilder代替。

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

相关问题

答案 2 :(得分:0)

你检查过java.util.Formatter吗?它的价格是1.5 btw。