Using a variable in a Java case statment

心已入冬 提交于 2021-02-16 19:37:11

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/29216034/using-a-variable-in-a-java-case-statment

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!