首页 > 解决方案 > 比较对象并分配正确的值

问题描述

您好,我正在尝试为我的班级比较两个支票账户对象的余额,但我遇到了一些问题。

 public int compareTo(Object other) {
  int otherBalance = 0;
  other = (Bankable) other;
  otherBalance = this.getBalance();
  if (otherBalance > getBalance()) {
     return otherBalance - getBalance();
  }
  else if (otherBalance < getBalance()) {
     return getBalance() - otherBalance;
  }
  else
     return 0;

}

上面的代码有一个逻辑错误,使得 otherBalance 等于错误对象的余额。这导致对该方法的调用总是返回 0。

我试图通过设置 otherBalance = other.getBalance(); 来纠正这个错误。但是这会返回编译器错误找不到符号。如果您能解释为什么会这样,我将不胜感激。

标签: javaobject

解决方案


这条线

other = (Bankable) other;

对你没有帮助,因为变量other仍然是 type Object,所以你仍然不能调用Bankable使用它的方法。

而是创建一个Bankable变量。

Bankable that = (Bankable) other;

然后你可以打电话

int otherBalance = that.getBalance();

推荐阅读