Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
949 views
in Technique[技术] by (71.8m points)

switch statement - Using a variable in a Java case statment

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.

question from:https://stackoverflow.com/questions/65948872/can-we-use-array-element-as-switch-case-in-java

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...