java - 比较对象并分配正确的值
问题描述
您好,我正在尝试为我的班级比较两个支票账户对象的余额,但我遇到了一些问题。
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(); 来纠正这个错误。但是这会返回编译器错误找不到符号。如果您能解释为什么会这样,我将不胜感激。
解决方案
这条线
other = (Bankable) other;
对你没有帮助,因为变量other
仍然是 type Object
,所以你仍然不能调用Bankable
使用它的方法。
而是创建一个Bankable
变量。
Bankable that = (Bankable) other;
然后你可以打电话
int otherBalance = that.getBalance();
推荐阅读
- javascript - 如何编写猫鼬更新来更新整个文档,包括各种子文档
- go - 将 go 文件放在模块路径上是一个好习惯吗?
- sorting - 谷歌表格 - 查询,添加一个单元格以隐藏一行
- tensorflow - 使用 image_dataset_from_directory 时出现 OOM
- git - 在 mysite.com/ 部署 GitHub Pages 站点
- dapper - 使用 Dapper SQL Builder 的 BETWEEN 动态 WHERE 子句
- localhost - Gatsbyjs 开发 LOCAL HOST 加载慢,慢 15 分钟
- php - 按小时和帖子分组(多个)
- eclipse-plugin - 如何在 MenuManger 中动态隐藏菜单
- asynchronous - 如何使用只有 BroadcastBlock 和 ActionBlock 的数据流