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

时间:2018-07-11 16:50:44

标签: 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;
}

}

扩展帐户:

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 个答案:

答案 0 :(得分:6)

让我们一步一步来

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"

如果我错了,请纠正我。