2012-11-24 16 views
1

我在想,如果你能做到以下幾點:用printf的格式打印時的數組對象

System.out.printf("%10.2f", car[i]); 

考慮到我已經重新定義了toString()方法。

public void toString() { 
    return this.getPrice + "" + this.getBrandName; 
} 

否則您如何格式化打印的價格?

回答

1

由於toString()返回一個String,可以用%ssee this),但不%fsee 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 

(代表美分的價格,如果它更容易。)

0

改爲使用String.format()

public void toString() { 
    return String.format("%10.2f", this.getPrice) + "" + this.getBrandName; 
}