Java格式化打印 [英] Formatted printing in Java
本文介绍了Java格式化打印的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有这段代码:
public String toString(Day day)
{
String s = day.getDayName() + " " + day.toString();
return s;
}
这是Day类的toString方法:
This is Day class's toString method:
public String toString()
{
String s = "";
for (Slot slot: slots)
s += slot.toString();
return s;
}
一遍又一遍地调用它打印:
When called over and over again it prints:
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:
但是,我想以这种方式打印:
However, I would like to print it this way:
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中。但我不知道如何做到这一点。
I know this works with formatted printing in Java. But I have no clue how to do that.
推荐答案
你可以使用 String.format()
,这将接受宽度。
You could use String.format()
, which will accept widths.
我认为你可以改变:
String s = day.getDayName() + " " + day.toString();
to:
return String.format("%9s %s", day.getDayName(), day.toString());
并得到你想要的。
这篇关于Java格式化打印的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文