我想知道您是否可以执行以下操作:
System.out.printf("%10.2f", car[i]);
考虑到我已经重新定义了toString()
方法。
public void toString() {
return this.getPrice + "" + this.getBrandName;
}
否则你如何格式化你打印的价格?
由于toString()
返回 a ,您可以使用(参见 this)而不是(参见 thisString
)格式化打印的对象。%s
%f
您可以将价格作为浮点数获取,并将格式化的数字与品牌一起打印:
class Car {
public String toString() {
return "I'm a car";
}
public double getPrice() {
return 20000.223214;
}
public String getBrandName() {
return "Brand";
}
}
class Main {
public static void main(String[] args) {
Car c = new Car();
System.out.printf("%10.2f %s", c.getPrice(), c.getBrandName());
}
}
输出
20000.22 Brand
(如果更容易,请以美分表示价格。)
请改用String.format()。
public void toString() {
return String.format("%10.2f", this.getPrice) + "" + this.getBrandName;
}