简体   繁体   中英

Getting an "Operator '&&' cannot be applied to 'boolean', 'int'" error and I'm unsure why

I'm writing a method that is to determine if two "Course" objects, where a "Course" object is comprised of courseName (String), department (String), code (int), section (byte), and instructor (String), and returns "true" if the objects have equivalent values. However, in the portion of the method that checks if they original "Course" object and the new "Course" object are equal, I am getting the above error.

Code for reference:

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;
}

Error is listed as being on the line if(this.courseName.equals(course.getName()) && , but I'm unsure if it's referring to the entire if statement.

Thank you!

The error is referring to the entire if statement. Byte.compare() returns an int , which cannot be used with logical operators.

For primitive byte values, you can just use == :

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;
}

Also note that you have a NullPointerException risk in your string comparisons.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM