Java – Compare enumeration values

Compare enumeration values… here is a solution to the problem.

Compare enumeration values

To implement the midfix of the suffix calculator, you need to check whether the operator has a lower priority than another operator. Here’s what I have so far:

public enum Operators {

ADD('+', 2), SUBTRACT('-', 2), MULTIPLY('*', 4), DIVIDE('/', 4);

private char operator;
    private int precedence;

Operators(char operator, int precedence) {
        this.operator = operator;
        this.precedence = precedence;
    }

public char getOperator() {
        return operator;
    }

public int getPrecedence() {
        return precedence;
    }
}

private static boolean isOperator(char c) {
    return c == Operators.ADD.getOperator() || c == Operators.SUBTRACT.getOperator()
            || c == Operators.MULTIPLY.getOperator() || c == Operators.DIVIDE.getOperator();
}

private static boolean isLowerPrecedence(char ch1, char ch2) {
     STUCK HERE
}

I’ve tried a lot of different ways to check the priority of incoming characters, but to no avail. Is there an easy way to compare two values of an enumeration? Do I have to create a loop?

Solution

If you have a way to convert the “operator” char to an enumeration value, it’s easy to compare.

For example:

static Operators getOperatorForChar(char op) {
    for(Operators val: values())
        if(op == val.operator)
            return val; return enum type

return null;
}

You can then implement your method using the following method:

private static boolean isLowerPrecedence(char ch1, char ch2) {

assuming intention is to compare precedence of ch1 to that of ch2
    return getOperatorForChar(ch1).precedence < getOperatorForChar(ch2).precedence;
}

Related Problems and Solutions