首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >防止添加的变量超过指定的数目

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

Stack Overflow用户
提问于 2014-12-12 20:14:45
回答 2查看 201关注 0票数 0

我正在努力使我的方法,payGourmet和payEconomical平衡不会改变,如果没有足够的钱,也不要下降到零以下。同时,我的loadMoney方法不会超过150,但仍然会从主目录中添加指定的数字。我做错了什么?

代码语言:javascript
复制
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);

}

}

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2014-12-12 20:19:42

当您检查余额是否大于0,然后减去一个金额时,您最终可能会出现负余额:

代码语言:javascript
复制
public void payEconomical() {
  if (this.balance > 0) {
    this.balance -= 2.5;
  }
}

如果balance = 1,这将产生负平衡(-1.5)。

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

代码语言:javascript
复制
public void payEconomical() {
  if (this.balance >= 2.5) {
    this.balance -= 2.5;
  }
  else {
    // There isn't enough money
  }
}

同样适用于payGourmet

代码语言:javascript
复制
if (this.balance >= 4.0) {
...

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

代码语言:javascript
复制
if (this.balance + amount <= 150.0) {
  this.balance += amount;
}
else {
  // Amount too large.
}
票数 1
EN

Stack Overflow用户

发布于 2014-12-12 20:20:45

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

代码语言:javascript
复制
int valueA = -50;

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

int valueB = 200;

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

如果要将其限制在上下界,只需使用这两种方法。

代码语言:javascript
复制
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

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

代码语言:javascript
复制
public void loadMoney(double amount) {
    this.balance = Math.min(this.balance + amount, 150);
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/27451435

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档