比如有个公式 String formula = "x=a*b"
x=Result amount
a = input
b = precent
我要把公式换成对应的字符串,怎么做?
String relplace会有问题,
for( ){
formula = formula.replace(x,"Result amount");
}
第二次replace时,formula =“ Result amount = a*b ”
formula = formula.replace(a,"input");
结果成了这样formula = "Result inputmount = input *b"
求帮忙解决!!
------解决方案--------------------
String formula = "x=a*b";
String x = "Result amount";
String a = "input";
String b = "precent";
System.out.println(formula.replace("x", x).replace("=a","="+a).replace("*b","*"+b));
ScriptEngineManager factory = new ScriptEngineManager();
ScriptEngine engine = factory.getEngineByName("JavaScript");
String script=" function hello(){";
script+=" var x='Result amount';";
script+=" var a='input';";
script+=" var b='precent'; ";
script+=" return (x+'='+a+'*'+b);";
script+=" }";
engine.eval(script);
Invocable inv = (Invocable) engine;
Object obj = inv.invokeFunction("hello");
System.out.println(obj);
------解决方案--------------------
String formula = "x=a*b ";
formula = formula.replace("x", "Result amount");
formula = formula.replace("a*", "input ");
formula = formula.replace("b", "precent");
把第二个替换改成这样就行了撒,或者就用正则表达式