-4 java oop if-statement
所以我几乎完全理解方法,对象和OOP.然而,我正在为初学者准备一本德语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;
}
}
Run Code Online (Sandbox Code Playgroud)
扩展帐户:
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!");
}
}
}
Run Code Online (Sandbox Code Playgroud)
测试帐户的代码:
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());
}
}
Run Code Online (Sandbox Code Playgroud)
输出:
Balance: -1000.0
Error - Account limit is exceded!
Balance: 10000.0
Run Code Online (Sandbox Code Playgroud)
原始代码也是用德语编写的,所以我希望我的代码翻译很容易理解!:)感谢先进的帮助.
让我们一步一步来.
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"
Run Code Online (Sandbox Code Playgroud)
如果我错了请纠正我.