我有一个包含键和值的 HashMap <String, String>
.
即 map 值:
mapValue.put("A","B-7");
mapValue.put("B","START+18");
mapValue.put("C","A+25");
现在我想计算 'C'
的表达式。所以对于C
,表达式为
替换为(((START+18)-7)+25)
.
因此,如果有任何方法,我将传递字符串 C
,它应该返回字符串
"(((START+18)-7)+25)"
我还想根据优先级对其进行评估。
谢谢
最佳答案
此类函数的一般逻辑(假设您知道可能的操作并且语法是严格的)可能如下:
public String eval(HashMap<String, String> mapValue, String variable) {
//get expression to be evaluated
String tmp = mapValue.get(variable);
// For each knwon operation
for (String op : OPERATIONS) {
// split expression in operators in Array
String[] vars = tmp.split("\\" + op);
// for each Element of splitted expr. Array
for (int i = 0; i < vars.length; i++) {
//Check if Element is a valid key in HashMap
if (mapValue.containsKey(vars[i])) {
//if it is replace element with result of iteration
vars[i] = eval(mapValue, vars[i]); // DO ITERATION
}
//if Element is not a valid key in has do nothing
}
//Join splitted string with proper operator
tmp = join(vars, op);
}
//return in parenthesis
return "(" + tmp + ")";
}
“eval(mapValue,"C")”的结果将是:
(((START+18)-7)+25)
一些短连接函数可以实现如下:
public String join(String[] arr, String d) {
String result = arr[0];
int i = 1;
while (i < arr.length) {
result += d + arr[i];
i++;
}
return result;
}
上面提供的所有代码更多的是为了说明逻辑,因为应该使用一些异常处理、更好的字符串操作等。
希望对你有帮助
干杯!
关于java - 从映射中递归查找字符串的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28089194/