Search code examples
javabluej

Bad operand types for binary type using Mutator in Java


I'm a beginner to Java programming. I'm using the BlueJ IDE. I can't seem to figure out what's wrong with this mutator. The error message says bad operand types for binary types.

/**
 * Sets the period of this course.
 */
public void setPeriod(String period)
{
    if(period = "A"|| "B" || "C" || "D")
    {
        this.period = period;
    }
} // end of mutator setPeriod(String period)

Solution

  • Your if statement expression is incorrect. Separate test expressions need to be delimited with the logical || operator.

    Also use String.equals for comparing String content. The assignment operator = is is used to assign values.

    if (period.equals("A") || period.equals("B") || 
                              period.equals("C") || period.equals("D")) {
    

    or better

    if ("A".equals(period) || "B".equals(period) || 
                              "C".equals(period) || "D".equals(period)) {
    

    This will protect against NullPointerException should period be null