You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

问题分析与修复步骤

  1. 对象不能直接和整数比较:你在if判断里直接用October(auditorForum类的实例)和整数1000比较,Java不允许对象与基本数据类型直接做大小比较,必须访问对象的pastMonthSpend属性来进行判断。
  2. 构造函数赋值顺序错误:构造函数里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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 00:15:48