使用String.format对齐toString()语句并在其中加入逗号

时间:2016-11-04 21:22:12

标签: java printf tostring string.format

所以我有一个由四个班级组成的课程。一个Boat超类,SailBoat和PowerBoat子类,以及一个测试程序,我有一个不同的帆船和动力艇的arrayList。

我有一个在SailBoat类中看起来像这样的toString()方法,PowerBoat具有相同的一个excpet,它取代了引擎大小的帆数。

public String toString()
   {
      return super.toString() + " Number of Sails = " + numSails + " Price = " + calcPrice();
   }

在我的测试课中,我必须打印出我所拥有的船只的ArrayList。目前我这样做:

for(Boat b: boats)
  {
     System.out.printf(b.toString());
     System.out.printf("\n");
  }

这会返回我的船只列表,但它根本没有对齐,看起来像这样:

Color = blue Length = 22 Engine Size = 60 Price = 12800.0
Color = white Length = 20 Number Sails = 1 Price = 22000.0
Color = red Length = 42 Number Sails = 3 Price = 48000.0
Color = yellow Length = 35 Engine Size = 80 Price = 17100.0
Color = red Length = 50 Engine Size = 120 Price = 22400.0
Color = blue Length = 33 Number Sails = 2 Price = 37000.0
Color = white Length = 20 Engine Size = 10 Price = 11200.0

我希望它看起来像(*应该代表填充或空格持有者):

Color = blue   Length = 22  Engine Size = *60  Price = $ 12,800.00
Color = white  Length = 20  Number Sails = *1  Price = $ 22,000.00
Color = red    Length = 42  Number Sails = *3  Price = $ 48,000.00
Color = yellow Length = 35  Engine Size = *80  Price = $ 17,100.00
Color = red    Length = 50  Engine Size = 120  Price = $ 22,400.00
Color = blue   Length = 33  Number Sails = *2  Price = $ 37,000.00
Color = white  Length = 20  Engine Size = *10  Price = $ 11,200.00

我知道我应该在String方法上使用String.format(),但是我在Oracle网站和其他地方看到的所有示例对我都没有任何意义,也没有向我显示将它们应用于toString方法。一些帮助将不胜感激......

1 个答案:

答案 0 :(得分:0)

String color1 = "yellow";
int length1 = 33;
String color2 = "red";
int length2 = 333;
System.out.println(String.format("Color = %-10s Length = %5d", color1, length1));
System.out.println(String.format("Color = %-10s Length = %5d", color2, length2));

以上是您可以尝试的最小示例。您只需要固定长度的占位符(您可以指定)。并且减号的存在与否表明文本左对齐或右对齐。