Compare value of enum

this_is_cat :

Implementing a infix to postfix calculator and need to check if an operator has a lower precedence than another. 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 number of different things to check the precedence of the char that is passed in but to no avail. Is there an easy way to compare two values of an enum? Will I have to create a loop?

ernest_k :

It's easy to compare if you have a method that translates a "operator" char to an enum value.

For example:

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

    return null;
}

And then you can implement your method using:

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

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=97310&siteId=1