获取“运算符'&&'不能应用于'boolean','int'”错误,我不确定为什么

问题描述

我正在编写一种方法,以确定是否两个“ Course”对象,其中“ Course”对象由courseName(字符串),部门(字符串),代码(int),部分(字节)和教师(字符串),如果对象具有相等的值,则返回“ true”。但是,在检查原始“ Course”对象和新的“ Course”对象是否相等的方法部分中,出现了以上错误

参考代码

public boolean equals(Course obj){
    if(obj instanceof Course){

        Course c = (Course)obj;

        if(this.courseName.equals(course.getName()) &&
                this.department.equals(course.getDepartment()) &&
                (this.code==course.getCode()) &&
                (Byte.compare(this.section,course.getSection())) &&
                this.instructor.equals(course.getInstructor()))
            return true;
    }
    return false;
}

错误被列为if(this.courseName.equals(course.getName()) &&行,但是我不确定它是否指向整个if语句。

谢谢!

解决方法

错误是指整个if语句。 Byte.compare()返回一个int,它不能与逻辑运算符一起使用。

对于原始byte值,您可以只使用==

if(this.courseName.equals(course.getName()) &&
        this.department.equals(course.getDepartment()) &&
        this.code == course.getCode() &&
        this.section == course.getSection() &&
        this.instructor.equals(course.getInstructor())) {
   
    return true;
}

还请注意,在字符串比较中存在NullPointerException的风险。