ticmy,你好,上次因为jexl在解决公式中含有小数的问题时,出了问题(http://topic.csdn.net/u/20110516/17/567b29dc-bf84-424f-95c7-a23bb4692152.html)我改成了js,这个问题可以解决了,但是又出现一个新的问题,如果公式中的数据复杂时,计算总是不正确,麻烦再帮我看看谢谢import java.util.HashMap;
import java.util.Map;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
public class TestSimpleExIf
{
public static void main(String[] args) throws ScriptException
{
Map<String, String> map = new HashMap();
map.put("x", "54.1");
map.put("y", "545563.45");
map.put("z", "75555.53");
map.put("d", "25555.64");


String exp = "if([[x]]>5,\"上升\"+([[z]]-[[d]]+[[y]]/2+[[y]]),\"下降\"+(-([[y]]-[[x]])))"; exp=exp.replaceAll("if\\((.*?),(.*?),(.*?)\\)","\\(\\($1\\)?$2:$3\\)"); exp = exp.replaceAll("\\[", "").replaceAll("\\]", ""); ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine scriptEngine = manager.getEngineByName("js");

for (int k = 0; k < map.keySet().size(); k++)
{
Object key = map.keySet().toArray()[k];
Object value = map.get(key);
scriptEngine.put(key.toString(), value.toString());
}

Object result = scriptEngine.eval(exp);
System.out.println("结果:" + result );


}
  
}

解决方案 »

  1.   

    原因是你在Map中添加的是字符串,它按字符串连接来做了
    public static void main(String[] args) throws ScriptException {
    Map<String, Object> map = new HashMap();
    map.put("x", 54.1);
    map.put("y", 545563.45);
    map.put("z", 75555.53);
    map.put("d", 25555.64);
    String exp = "if([[x]]>5,\"上升\"+([[z]]-[[d]]+[[y]]/2+[[y]]),\"下降\"+(-([[y]]-[[x]])))"; exp=exp.replaceAll("if\\((.*?),(.*?),(.*?)\\)","\\(\\($1\\)?$2:$3\\)"); exp = exp.replaceAll("\\[", "").replaceAll("\\]", "");
    System.out.println(exp);
    ScriptEngineManager manager = new ScriptEngineManager();
    ScriptEngine scriptEngine = manager.getEngineByName("js"); for (int k = 0; k < map.keySet().size(); k++)
    {
    Object key = map.keySet().toArray()[k];
    Object value = map.get(key);
    scriptEngine.put(key.toString(), value);
    }

    Object result = scriptEngine.eval(exp);
    System.out.println("结果:" + result );
    }
      

  2.   

    主要注意这一句:scriptEngine.put(key.toString(), value);value该是什么类型就是什么类型