2016-03-24 25 views
0

我被要求實現printDailyCost方法,該方法應調用getDailyCost方法並將返回值的格式設置爲返回兩個小數位數 。它應該隨着一個英鎊符號打印這個值。Java printDailyCost方法

到目前爲止,我有:

public abstract class Suit { 

    private String colour; 
    private double dailyCost; 
    private int trouserLength; 
    private int jacketChestSize; 
    private boolean available; 
    private double totalPrice; 

    public Suit(String colour, double dailyCost, int trouserLength, 
       int jacketChestSize, boolean available, double totalPrice) { 
     super(); 
     this.colour = colour; 
     this.dailyCost = dailyCost; 
     this.trouserLength = trouserLength; 
     this.jacketChestSize = jacketChestSize; 
     this.available = available; 
     this.totalPrice = totalPrice; 
    } 

    public String getColour() { 
     return colour; 
    } 

    public double getDailyCost() { 
     return dailyCost; 
    } 

    public int getTrouserLength() { 
     return trouserLength; 
    } 

    public int getJacketChestSize() { 
     return jacketChestSize; 
    } 

    public boolean isAvailable() { 
     return available; 
    } 

    public double getTotalPrice() { 
     return totalPrice; 
    } 

    public void setColour(String colour) { 
     this.colour = colour; 
    } 

    public void setDailyCost(double dailyCost) { 
     this.dailyCost = dailyCost; 
    } 

    public void setTrouserLength(int trouserLength) { 
     this.trouserLength = trouserLength; 
    } 

    public void setJacketChestSize(int jacketChestSize) { 
     this.jacketChestSize = jacketChestSize; 
    } 

    public void setAvailable(boolean available) { 
     this.available = available; 
    } 

    public void setTotalPrice(double totalPrice) { 
     this.totalPrice = totalPrice; 
    } 

    public void calcTotalPrice(int numDaysHired){ 
     this.totalPrice = dailyCost * numDaysHired; 
    } 

    public String printDailyCost() { 
     return printDailyCost();   
    } 
} 

我的問題是如何將我修改我的printDailyCost方法調用getDailyCost方法和格式化返回值兩個 小數然後用£標誌打印?

回答

1

您可以將它們相加,並返回:

public String printDailyCost() { 
    return getDailyCost() + " £";   
} 

不過我不建議來連接String用這種方式。更好地利用使用StringBuilder下面的方法,即連接字符串以正確的方式:

public String printDailyCost() { 
    return (new StringBuilder().append(getDailyCost()).append(" £")).toString();   
} 

或者,如果你想打印出來安慰,只是這樣做:

System.out.println(getDailyCost() + " £"); 
+0

謝謝你幫助我! –

2

檢查了這一點:

java.text.NumberFormat format = java.text.NumberFormat.getCurrencyInstance(java.util.Locale.UK); 
    System.out.println(format.format(getDailyCost()));