仅打印 Java 中的非负余额

Print only non-negative balance in Java

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

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

//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;
        }    
    }
}

而不是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);
    }
}

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

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;
    } 

}