仅用Java打印非负余额



我目前正在解决中的PaymentCard练习https://java-programming.mooc.fi/part-4/1-introduction-to-object-oriented-programming并且该程序的输出不应该是负平衡。如果余额为负数,则不会打印。我在两个方法中都添加了一个条件语句,但我的输出一直打印负平衡。

任何帮助都将不胜感激。谢谢

//Desired Output:The card has a balance 5.0 euros
//              The card has a balance 0.40000000000000036 euros
//              The card has a balance 0.40000000000000036 euros
//My Output: The card has a balance of 5.0 euros
//           The card has a balance of 0.40000000000000036 euros
//           The card has a balance of -4.199999999999999 euros
public class MainProgram {
public static void main(String[] args) { 
PaymentCard card = new PaymentCard(5);
System.out.println(card);
card.eatHeartily();
System.out.println(card);
card.eatHeartily();
System.out.println(card);
}
}
public class PaymentCard {
private double balance;
public PaymentCard(double openingBalance) {
this.balance = openingBalance;
}
public String toString() {
return "The card has a balance of " + this.balance + " euros";
}
public void eatAffordably() {
if (this.balance > 0) {
this.balance = this.balance - 2.60;
}   
}
public void eatHeartily() {
if (this.balance > 0) {
this.balance = this.balance - 4.60;
}    
}
}

显然,您只能打印大于零的金额,但是我认为一个更正确和优雅的解决方案是考虑你减去的金额:

public void eatAffordably() {
if (this.balance >= 2.60) {
this.balance = this.balance - 2.60;
} 
}
public void eatHeartily() {
if (this.balance >= 4.60) {
this.balance = this.balance - 4.60;
} 
}

而不是使用toString方法

public String toString() {
return "The card has a balance of " + this.balance + " euros";
}

并调用System.out.println(card);

创建一种进行实际打印的方法,例如

void printCard () {
if (this.balance > 0) {
System.out.println(card);
}
}

最新更新