我最近开始面向对象编程,并一直在尝试做一个椅子类,该类应该打印出属性,即材料、腿、颜色和价格。我已经很好地完成了前三个,但是我很难在主类中以美元形式输出价格。
这是我的主持课:
class Chair {
private String material;
private String colour;
private int legs;
private double price;
public void setMaterial(String material) {
this.material = material;
}
public void setColour(String colour) {
this.colour = colour;
}
public void setLegs(int legs) {
this.legs = legs;
}
public void setPrice(double price) {
this.price = price;
}
@Override
public String toString() {
return "This is a " + this.colour + " " + this.material + " chair that has " + this.legs + " legs and costs $" + this.price;
}
}
这是我的主课:
class Main {
public static void main(String[] args) {
Chair c = new Chair();
c.setMaterial("steel");
c.setColour("purple");
c.setPrice(50);
c.setLegs(4);
System.out.println(c);
}
}
我试图将 50 输出为 50.00,但无论我尝试什么,我都只能得到这个输出:这是一把紫色钢椅,有 4 条腿,售价 50.0 美元
我对 OOP 很陌生,所以我不理解某些概念,而且我已经很多年没有用 Java 编码了,所以这对我来说很陌生,我很抱歉。
您的问题与 OOP 概念无关。您想要的是将浮点数格式化为小数点后两位数字的货币格式。在 Java 中,您可以使用
DecimalFormat
来执行此操作。
在下面的代码中,
return "This is a " + this.colour + " " + this.material + " chair that has " + this.legs + " legs and costs $" + this.price;
将
this.price
替换为
new DecimalFormat("#0.00").format(this.price)
这里,模式 #0.00 表示小数点前至少 1 位,小数点后正好 2 位。
注意 - 我相信这只是您尝试学习 Java 时的玩具程序。但请注意,要存钱,请使用
BigDecimal
或更好的东西来代替 float
或 double
。