Renasha Silva
Renasha Silva

Reputation: 29

bad operand types for binary operator. i am getting that error for the below program. please explain why?

public class MotorCar extends Vehicle
{
    private String engCap;

    public double getLicenseFee()
    {
        double fee;

        if(this.engCap < "1500cc")
        {
            return fee = 750;
        }
        else if(this.engCap > "1500cc" && this.engCap < "2500cc")
        {
            return fee = 900;
        }
        else(this.engCap > "2500cc")
        {
            return fee = 1250;
        }

    }

}

what is wrong with this?

Upvotes: 0

Views: 648

Answers (2)

rgettman
rgettman

Reputation: 178333

In Java, you cannot use the "<" and ">" (and "<=" and ">=") operators on Strings. To compare the values, use the String#compareTo method, which will return an integer less than zero, equal to zero, or greater than zero, depending on if the String compares less than equal to, or greater than the argument.

Be careful, because this is string comparison, "500cc" will be greater than "1500cc".

EDIT

If you are attempting to determine a range based on the integer portion of engCap, then it would be simpler to go with @thegrinner's answer, and just store the numeric value without the "cc". Then you could use the operators you're attempting to use.

Upvotes: 2

thegrinner
thegrinner

Reputation: 12241

You cannot compare strings (or any other objects) using the less-than < and greater-than > operators.

If you change your engCap variable to an int and drop the "cc" portion, you'll be able to compare it the way you're attempting to.

For example:

public class MotorCar extends Vehicle {
    private int engCap;

    public double getLicenseFee() {
        double fee;

        if(this.engCap < 1500) {
            return fee = 750;
        } else if(this.engCap > 1500 && this.engCap < 2500) {
            return fee = 900;
        } else(this.engCap > 2500) {
            return fee = 1250;
        }
    }
}

Upvotes: 3

Related Questions