我正在努力使我的方法,payGourmet和payEconomical平衡不会改变,如果没有足够的钱,也不要下降到零以下。同时,我的loadMoney方法不会超过150,但仍然会从主目录中添加指定的数字。我做错了什么?
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);
}}
发布于 2014-12-12 20:19:42
当您检查余额是否大于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.
}发布于 2014-12-12 20:20:45
若要将值限制为最小值或最大值,请使用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);
}https://stackoverflow.com/questions/27451435
复制相似问题