【发布时间】:2018-11-16 22:00:46
【问题描述】:
所以我得到了一项任务,要编写一个计数器,将给定数量的美元和美分加在一起。我们获得了一个用于测试功能的测试类。
我们得到了以下提示:
public int dollars () //The dollar count.
ensure: this.dollars () >= 0
public int cents () //The cents count.
ensure: 0 <= this.cents() && this.cents() <= 99
还有:
public void add (int dollars, int cents) //Add the specified dollars and cents to this Counter.
public void reset () //Reset this Counter to 0.
ensure: this .dollars() == 0 && this.cents() == 0
这是我当前的代码:
public class Counter {
private float count;
public Counter() {
count = 0;
}
public int dollars() {
if (this.dollars() >= 0) {
count = count + Float.parseFloat(this.dollars() + "." + 0);
} return 0;
}
public int cents() {
if (0 <= this.cents() && this.cents() <= 99) {
count = count + Float.parseFloat(+0 + "." + this.cents());
} else if (100 <= this.cents()) {
count = count + Float.parseFloat(+1 + "." + (this.cents() - 100));
}
return 0;
}
public void add(int dollars, int cents) {
dollars = this.dollars();
cents = this.cents();
}
public void reset() {
count = 0;
}
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
}
}
我意识到我在这里犯了错误(据说是在浮动并试图计算浮动的美元和美分部分)。但我无法准确指出它失败的地方。
【问题讨论】:
-
你的
main()方法是空的,对于初学者来说。 -
我不确定这对功能有何影响,因为测试类是从另一个类完成的。
-
那你为什么有它?真正的问题是什么?
-
问题太多:(1) 在
dollars()内部调用dollars()导致无限递归(cents相同)。 (2) 几乎在任何地方都向count添加值,除了应该做的地方。可能还有更多。 -
@user3757962 提示:不要使用
float表示货币值。在这种情况下,您应该将字段count更改为 int 并计算美分的数量(将美元转换为美分,并在需要时将它们转换回来)