【问题标题】:Using String.format to align toString() statements and put commas within them使用 String.format 对齐 toString() 语句并在其中放置逗号
【发布时间】:2016-11-04 21:22:11
【问题描述】:

所以我有一个由四个类组成的程序。一个 Boat 超类、SailBoat 和 PowerBoat 子类,以及一个测试程序,其中我有一个包含不同风帆和摩托艇的数组列表。

我有一个 toString() 方法,在 SailBoat 类中看起来像这样,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

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

【问题讨论】:

标签: java printf tostring string.format


【解决方案1】:
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));

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

【讨论】:

  • 我应该提到,这是我的一个编程课程中的一个实验室。我的程序正在运行,但它表示需要将 String.format 语句应用于所有 toString 方法的格式。这是您在上面所做的,还是只是创建新属性并将其应用于它们?
  • @AbbeyS 在您的toString 方法中,只需返回String.format("MyFormat", value1, value2, ...)
猜你喜欢
  • 1970-01-01
  • 2021-10-06
  • 1970-01-01
  • 1970-01-01
  • 2011-02-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多