我想知道你是否可以做到以下几点:
System.out.printf("%10.2f", car[i]);
考虑到我重新定义了toString()
方法。
public void toString() {
return this.getPrice + "" + this.getBrandName;
}
否则你如何格式化你打印的价格?
答案 0 :(得分:1)
由于toString()
会返回String
,您可以使用%s
(see this)而不是%f
(see this)格式化打印对象
您可以将价格作为浮点数并打印格式化的数字以及品牌:
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
(如果更容易,则以美分代表价格。)
答案 1 :(得分:0)
改为使用String.format()。
public void toString() {
return String.format("%10.2f", this.getPrice) + "" + this.getBrandName;
}