因此,我正在编写一个应该模拟飞机货物的类,并且无法格式化类的toString()方法。下面的代码:格式化字符串
public class Cargo
{
private String label;
private int weight, height, width, length;
public String toString()
{
return String.format("%s%s\t\t%-7s%-2s%-5d%-11s%-2s%-3d%-2s%-3d%-2s%d",
getLabel(), ":", "Weight", "=", getWeight(), "Dimensions",
"=", getHeight(), "X", getWidth(), "X", getLength());
}
public static void main(String[] args)
{
Cargo cargo1 = new Cargo("Bill's Beans", 1200, 20, 15, 30);
Cargo cargo6 = new Cargo("Chicago Bulls", 1000, 10, 10, 10);
Cargo cargo7 = new Cargo("Lots of Meat", 3000, 20, 20, 20);
Cargo cargo8 = new Cargo("Tammy's Tomatoes", 600, 6, 6, 6);
System.out.println(cargo1.toString());
System.out.println(cargo6.toString());
System.out.println(cargo7.toString());
System.out.println(cargo8.toString());
}
}
产生这样的输出:
Bill's Beans: Weight = 1200 Dimensions = 20 X 15 X 30
Chicago Bulls: Weight = 1000 Dimensions = 10 X 10 X 10
Lots of Meat: Weight = 3000 Dimensions = 20 X 20 X 20
Tammy's Tomatoes: Weight = 600 Dimensions = 6 X 6 X 6
正如你所看到的,一切良好比对,除了 “陈怡蓉的西红柿。”我怎样才能解决这个问题?谢谢。
%s%s之后的额外选项卡可能适用于您。 – Bhushan