K_Azusa 2022-03-20 21:52 采纳率: 50%
浏览 21

Java里,为什么在一个类中定义几个成员变量后,不能使其中一个成员变量等于其他几个成员变量之和?

自己定义的学生类,其中包括语文,数学,英语成绩,并定义mix(总分)等于前三者之和。

img

虽然编译器没报错,但实际运行过程中会出现mix还是0的结果。

img

这个问题,困扰我很久了,虽然最后用mixget方法解决了但这个困惑还是不清楚,求解答!
附代码:

public class studentDate implements Comparable {
    private String name;
    private int chinese;
    private int math;
    private int English;
    private int mix =chinese + math +English;

    public studentDate() {
    }
    public studentDate(String name, int chinese, int math, int english) {
        this.name = name;
        this.chinese = chinese;
        this.math = math;
        English = english;
        this.mix = chinese + math +english;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getChinese() {
        return chinese;
    }
    public void setChinese(int chinese) {
        this.chinese = chinese;
    }
    public int getMath() {
        return math;
    }
    public void setMath(int math) {
        this.math = math;
    }
    public int getEnglish() {
        return English;
    }
    public void setEnglish(int english) {
        English = english;
    }
    public int getMix() {
        return mix;
    }
    public void setMix() {
        this.mix = mix=this.chinese + this.math + this.English;
    }

    @Override
    public int compareTo(Object o) {
        int a = mix - this.mix;
        if (a != 0) {
            return a;
        } else {
            return a = 1;
        }
    }
}
  • 写回答

3条回答 默认 最新

  • hfhua 2022-03-20 22:09
    关注

    定义的时候直接定义mix,把=及后面的删掉

    评论

报告相同问题?

问题事件

  • 创建了问题 3月20日

悬赏问题

  • ¥15 Python如何爬取post请求头的数据
  • ¥100 adb针对解决手机锁屏问题(相关搜索:手机锁屏)
  • ¥15 发现哔哩哔哩的粉丝只能显示前5页能不能爬出来
  • ¥15 oracle数据库求解
  • ¥15 c++ websocketpp连接币安 有报错,有偿求解
  • ¥20 提供开发板完整sdk文件,升级开发板函数库
  • ¥15 网页视频播放,无法播放
  • ¥15 pycharm时import matplotlib报错value error
  • ¥15 YOLO 5 打包 文件太大
  • ¥15 被google屏蔽ip