Using a variable in a Java case statment(在 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.
这篇关于在 Java 案例语句中使用变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在 Java 案例语句中使用变量
基础教程推荐
- REST Web 服务返回 415 - 不支持的媒体类型 2022-01-01
- Spring AOP错误无法懒惰地为此建议构建thisJoinPoin 2022-09-13
- 无法复制:“比较方法违反了它的一般约定!" 2022-01-01
- 使用堆栈算法进行括号/括号匹配 2022-01-01
- RabbitMQ:消息保持“未确认"; 2022-01-01
- 修改 void 函数的输入参数,然后读取 2022-01-01
- Struts2 URL 无法访问 2022-01-01
- 如何对 Java Hashmap 中的值求和 2022-01-01
- 问题http://apache.org/xml/features/xinclude测试日志4j 2 2022-01-01
- 存储 20 位数字的数据类型 2022-01-01
