有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

字符串Java printDailyCost方法

我被要求实现一个printDailyCost方法,该方法应该调用getDailCost方法并将返回的值格式化为2 小数位。然后,它将打印此值和一个符号

到目前为止,我已经:

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方法并将返回的值格式化为2 小数点后几位用“%号”打印


共 (2) 个答案

  1. # 1 楼答案

    看看这个:

        java.text.NumberFormat format = java.text.NumberFormat.getCurrencyInstance(java.util.Locale.UK);
        System.out.println(format.format(getDailyCost()));
    
  2. # 2 楼答案

    您可以简单地将它们添加在一起并返回:

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

    但是,我不建议用这种方式连接String。最好使用以下方法使用StringBuilder,以正确的方式连接字符串:

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

    或者,如果要将其打印到控制台,只需执行以下操作:

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