在 Java 中的表达式中使用字符
Use character in expression in Java
如何使用 Java 中的字符作为表达式,假设我有一个表达式
char ch = '+';
那么是否可以使用 ch 的值执行加法,而不使用 if-else 或 switch 或类似的东西?
我想使用 ch
作为表达式。如果 ch = '+'
,那么是否可以做类似 x = 5 ch 6
的事情来计算 5+6
?
我不确定是否推荐,但您可以使用 JavaScript 引擎。在下面找到一个技巧:
char op = '*';
String operand1= "10";
String operand2 = "20";
ScriptEngineManager scm = new ScriptEngineManager();
ScriptEngine jsEngine = scm.getEngineByName("JavaScript");
System.out.println(jsEngine.eval(operand1+op+operand2));
这会给你 200.0
一种不使用 if/else 或 switch 的方法是定义一个枚举:
enum Operator {
PLUS('+') {
@Override public int apply(int a, int b) { return a + b; }
}, TIMES('*') {
@Override public int apply(int a, int b) { return a * b; }
}, ... ;
static final Map<Character, Operator> map = buildMap();
final char ch;
private Operator(char ch) { this.ch = ch; }
public abstract int apply(int a, int b);
static Map<Character, Operator> buildMap() {
Map<Character, Operator> map = new HashMap<>();
for (Operator op : Operator.values()) {
map.put(op.ch, op);
}
return map;
}
}
然后使用它来处理您的输入:
Operator.map.get(ch).apply(leftOperand, rightOperand);
有以下方法
- ScriptEngineManager
- 使用 Java 词法分析器和解析器
- BeanShell 解释器
因为它已经回答了您可以在 Evaluating a math expression given in string form
中获得更多详细信息
如果你,Java 8中介绍的二元函数使这个代码非常优雅:
Map<Character, IntBinaryOperator> operators = new HashMap<>();
operators.put('+', (x, y) -> x + y);
//...
你这样使用这张地图:
char ch = '+';
int result = operators.get(ch).applyAsInt(10, 20);
尽管这可能不是您要查找的内容,因为它需要您将“+”映射到操作。
如何使用 Java 中的字符作为表达式,假设我有一个表达式
char ch = '+';
那么是否可以使用 ch 的值执行加法,而不使用 if-else 或 switch 或类似的东西?
我想使用 ch
作为表达式。如果 ch = '+'
,那么是否可以做类似 x = 5 ch 6
的事情来计算 5+6
?
我不确定是否推荐,但您可以使用 JavaScript 引擎。在下面找到一个技巧:
char op = '*';
String operand1= "10";
String operand2 = "20";
ScriptEngineManager scm = new ScriptEngineManager();
ScriptEngine jsEngine = scm.getEngineByName("JavaScript");
System.out.println(jsEngine.eval(operand1+op+operand2));
这会给你 200.0
一种不使用 if/else 或 switch 的方法是定义一个枚举:
enum Operator {
PLUS('+') {
@Override public int apply(int a, int b) { return a + b; }
}, TIMES('*') {
@Override public int apply(int a, int b) { return a * b; }
}, ... ;
static final Map<Character, Operator> map = buildMap();
final char ch;
private Operator(char ch) { this.ch = ch; }
public abstract int apply(int a, int b);
static Map<Character, Operator> buildMap() {
Map<Character, Operator> map = new HashMap<>();
for (Operator op : Operator.values()) {
map.put(op.ch, op);
}
return map;
}
}
然后使用它来处理您的输入:
Operator.map.get(ch).apply(leftOperand, rightOperand);
有以下方法
- ScriptEngineManager
- 使用 Java 词法分析器和解析器
- BeanShell 解释器
因为它已经回答了您可以在 Evaluating a math expression given in string form
中获得更多详细信息如果你
Map<Character, IntBinaryOperator> operators = new HashMap<>();
operators.put('+', (x, y) -> x + y);
//...
你这样使用这张地图:
char ch = '+';
int result = operators.get(ch).applyAsInt(10, 20);
尽管这可能不是您要查找的内容,因为它需要您将“+”映射到操作。