防止添加的变量超过指定的数量

时间:2014-12-12 20:14:46

标签: java increment

我试图做到这一点,所以我的方法付出美食和支付经济平衡不会改变,如果没有足够的钱,不要低于零。另外,我的loadMoney方法不超过150但仍然从main添加指定的数字。我究竟做错了什么?

Import java.util.Scanner;

public class LyyraCard {

private double balance;

public LyyraCard(double balanceAtStart) {
    this.balance = balanceAtStart;
}
public String toString() {
    return "The card has " + this.balance + " euros";
}
public void payEconomical() {
    if (this.balance > 0) {
        this.balance -= 2.5;
    }
}
public void payGourmet() {
    if (this.balance > 0) {
        this.balance -= 4.0;
    }
}

public void loadMoney(double amount) {
    if (this.balance < 150) {
        this.balance += amount;
    }

}

}

public class Main {

public static void main(String[] args) {
    // add here code that tests LyraCard. However before doing 77.6 remove the
    // other code 
    LyyraCard card = new LyyraCard(10);
    System.out.println(card);

    card.payEconomical();
    System.out.println(card);

    card.payGourmet();
    System.out.println(card);

    card.payGourmet();
    System.out.println(card);

    card.loadMoney(10);
    System.out.println(card);

    card.loadMoney(200);
    System.out.println(card);

}

}

2 个答案:

答案 0 :(得分:1)

当您检查余额是否大于0然后减去金额时,您可能会以负余额结束:

public void payEconomical() {
  if (this.balance > 0) {
    this.balance -= 2.5;
  }
}

如果balance = 1这会产生负余额(-1.5)。

您需要检查余额是否等于或大于您要减去的金额

public void payEconomical() {
  if (this.balance >= 2.5) {
    this.balance -= 2.5;
  }
  else {
    // There isn't enough money
  }
}

同样适用于payGourmet

if (this.balance >= 4.0) {
...

loadMoney中,您需要检查当前余额加上增加的金额是否等于或小于150:

if (this.balance + amount <= 150.0) {
  this.balance += amount;
}
else {
  // Amount too large.
}

答案 1 :(得分:0)

要将值限制为最小值或最大值,请使用Math.min()Math.max()

int valueA = -50;

valueA = Math.max(valueA, 0); //valueA is now 0;

int valueB = 200;

valueB = Math.min(valueB, 150); //valueB is now 150;

如果您想将其限制在上限下限,请使用两种方法

int valueC = -50;

valueC = Math.min(Math.max(valueC, 0), 150); //valueC is now 0

int valueD = 200;

valueD = Math.min(Math.max(valueC, 0), 150); //valueD is now 150

编辑:因此,对于您的示例,请使用

public void loadMoney(double amount) {
    this.balance = Math.min(this.balance + amount, 150);
}