Using a variable in a Java case statment

user1505399 picture user1505399 · Mar 23, 2015 · Viewed 7.7k times · Source

I am making an expression parser for a calculator. The expressions will contain a variable, for instance, a user could enter "x + 2", or "y^2". I have a switch statement, and one of the cases in switch statement performs a certain action when it detects a variable:

case variableSymbol:
                    if (expression.length() == 1) 
                    {
                        rangeResult = x1;
                        break outer;
                    }
                    varFlag = true;
                    varPos = expresPos;
                    break;

Originally, I hard coded a value 'x' in the above case, but I would like to give users a choice as to which variable they use, so added a char parameter to the parse function, and named it variableSymbol. This is these are the parameters for the function:

public static ArrayList<Double> parseRange(String expression, char variableSymbol, double x1, double x2, double step)

But Java doesn't allow variables as cases in switch statements. Is there any way around this? Solutions that avoid rewriting the switch statement are the best, since it is several hundreds of lines long.Thank you for your assistance.

Answer

Random42 picture Random42 · Mar 23, 2015

No, that is not possible and doesn't make sense for a switch case; what you want can be achieved with if-else. The reason is because switch is typically implemented with look-up tables, being more efficient than if-else; but in order to achieve this the branching needs to be set-up at compile time.