在Java案例陈述中使用变量 [英] Using a variable in a Java case statment

查看:65
本文介绍了在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语句中将变量作为大小写.有没有办法解决?避免重写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.

这篇关于在Java案例陈述中使用变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆