1

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!

Gabe M
  • 11
  • 2
  • What do you mean by `(Byte.compare(this.section, course.getSection()))`? Do you want to compare less than or greater than? – Sweeper Sep 02 '20 at 04:51
  • You also wrote Course instead of Object for the argument type. Use a tool that can generate equals for you. https://stackoverflow.com/questions/6959307/java-automatic-equals-and-hashcode – Brian McCutchon Sep 02 '20 at 04:56
  • There's also a mismatch between your `Course c` variable and the subsequent use of the `course` variable. – Robby Cornelissen Sep 02 '20 at 04:59
  • Byte.compare returns an int value. 0 in case if both values are equal so ...`(Byte.compare(this.section, course.getSection()) == 0)` – dream2work Sep 02 '20 at 05:09

1 Answers1

3

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.

Robby Cornelissen
  • 91,784
  • 22
  • 134
  • 156