为什么 -1000 >= -1000 在此代码中被解释为 false?



我在一本面向初学者的Java编程书中做了一个练习,我必须创建一个提款限额高达-1000欧元的银行账户。不知怎的,即使金额是-1000欧元,代码也执行else代码,这对我来说没有什么意义。在我看来,它不应该输出错误,但它确实输出了。

这是账户代码:

public class Account {
private String accountnumber;
protected double accountbalance;
Account(String an, double ab) {
accountnumber = an;
accountbalance = ab;  
}
double getAccountbalance() {
return accountbalance;
}
String getAccountnumber() { 
return accountnumber;
}

void deposit(double ammount) {
accountbalance += ammount;
}
void withdraw(double ammount) {
accountbalance -= ammount;
}
}

扩展帐户:

public class GiroAccount extends Account{
double limit;
GiroAccount(String an, double as, double l) {
super(an, as);
limit = l;
}
double getLimit() {
return limit;
}
void setLimit(double l) {
limit = l;
}
void withdraw(double ammount) {
if ((getAccountbalance() - ammount) >= limit) {
super.withdraw(ammount);
} else {
System.out.println("Error - Account limit is exceded!");
}
}
}

测试账户的代码:

public class GiroAccountTest {
public static void main(String[] args) {
GiroAccount ga = new GiroAccount("0000000001", 10000.0, -1000.0);
ga.withdraw(11000.0);
System.out.println("Balance: " + ga.getAccountbalance());
ga.deposit(11000.0);
ga.withdraw(11001.0);
System.out.println("Balance: " + ga.getAccountbalance());
}
}

输出:

Balance: -1000.0
Error - Account limit is exceded!
Balance: 10000.0

让我们循序渐进。

1. Start with 10000.0;
2. withdraw(11000.0) -> -1000.0
3. Print balance -> "Balance: -1000.0"
4. deposit(11000.0) -> 10000.0
5. withdraw(11001.0); -> -1001.0 < -1000.0
6. Overdrawn (enters else block) -> "Error - Account limit is exceeded"
7. Print balance -> "Balance: 10000.0"

如果我错了,请纠正我。

相关内容

最新更新