在 Java 案例语句中使用变量

我正在为计算器制作表达式解析器.表达式将包含一个变量,例如,用户可以输入x + 2"或y^2".我有一个switch语句,switch语句中的一种情况在检测到变量时会执行某个动作:

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;

最初,我在上面的例子中硬编码了一个值'x',但我想让用户选择他们使用哪个变量,所以在解析函数中添加了一个 char 参数,并将其命名为 variableSymbol.这是函数的参数:

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)

但是 Java 不允许变量作为 switch 语句中的 case.有没有办法解决?避免重写 switch 语句的解决方案是最好的,因为它有数百行长.感谢您的帮助.

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.

推荐答案

不,这是不可能的,对于 switch 的情况没有意义;if-else 可以实现你想要的.原因是因为 switch 通常使用查找表来实现,比 if-else 更有效;但为了实现这一点,需要在编译时设置分支.

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.

相关文章