I'm currently solving the PaymentCard exercise in https://java-programming.mooc.fi/part-4/1-introduction-to-object-oriented-programming and the output of this program should not be a negative balance. If ever the balance gets negative, it will not be printed. I added a conditional statement in both methods but my output keeps printing a negative balance.
Any help would genuinely be appreciated. Thanks!
//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;
}
}
}