Java对象与int比较报错:auditorForum类代码修正求助
Java对象与整数比较报错修复
你的代码
public class auditorForum { int pastMonthSpend; public auditorForum(int spending){ spending = pastMonthSpend; } public static void main(String[] args) { auditorForum October = new auditorForum(1433); if (October >= 1000) { if (October <= 1500){ System.out.println("Eligible"); } else { System.out.println("Ineligible"); } } } }
报错信息
auditorForum.java:9: error: bad operand types for binary operator '>=' if (October >= 1000) { ^ first type: auditorForum second type: int 1 error
问题分析与修复步骤
- 对象不能直接和整数比较:你在
if判断里直接用October(auditorForum类的实例)和整数1000比较,Java不允许对象与基本数据类型直接做大小比较,必须访问对象的pastMonthSpend属性来进行判断。 - 构造函数赋值顺序错误:构造函数里
spending = pastMonthSpend的写法逻辑颠倒,会把类属性的默认初始值0赋值给参数spending,而非把传入的参数值赋给pastMonthSpend,应该改为pastMonthSpend = spending。
修复后的代码
public class auditorForum { int pastMonthSpend; public auditorForum(int spending){ // 修正赋值顺序,将传入的参数值赋给类属性 pastMonthSpend = spending; } public static void main(String[] args) { auditorForum October = new auditorForum(1433); // 访问对象的pastMonthSpend属性进行数值比较 if (October.pastMonthSpend >= 1000) { if (October.pastMonthSpend <= 1500){ System.out.println("Eligible"); } else { System.out.println("Ineligible"); } } } }
可选优化(面向对象封装)
如果想让代码更符合面向对象的封装规范,可以给pastMonthSpend添加private修饰符,通过getter方法获取属性值:
public class auditorForum { private int pastMonthSpend; public auditorForum(int spending){ pastMonthSpend = spending; } // 提供getter方法获取属性值 public int getPastMonthSpend() { return pastMonthSpend; } public static void main(String[] args) { auditorForum October = new auditorForum(1433); if (October.getPastMonthSpend() >= 1000) { if (October.getPastMonthSpend() <= 1500){ System.out.println("Eligible"); } else { System.out.println("Ineligible"); } } } }
内容的提问来源于stack exchange,提问作者phylansalvador
相关产品推荐
相关产品推荐

