67,541
社区成员
发帖
与我相关
我的任务
分享import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
public class Calculator {
private static String parseExpress(String express) throws IllegalArgumentException {
if(express == null || express.trim().length() == 0) {
throw new IllegalArgumentException("参数非法,express:" + express);
}
Pattern pattern = Pattern.compile("(\\d+)\\%");
Matcher matcher = pattern.matcher(express);
while(matcher.find()) {
express = matcher.replaceAll("(" + matcher.group(1) + "*0.01)");
}
return express;
}
public static Object calculate(String exp) throws Exception {
exp = parseExpress(exp);
ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByName("jexl");
return engine.eval(exp);
}
public static void main(String... a) throws Exception {
Object result = calculate("10*2*40%*34/3");
System.out.println("结果:" + result + " ; 类型:" + result.getClass().getName());
}
} import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
public class Calculator {
private static String parseExpress(String express) throws IllegalArgumentException {
if(express == null || express.trim().length() == 0) {
throw new IllegalArgumentException("参数非法,express:" + express);
}
Pattern pattern = Pattern.compile("(\\d+)\\%");
Matcher matcher = pattern.matcher(express);
while(matcher.find()) {
express = matcher.replaceAll("(" + matcher.group(1) + "*0.01)");
}
return express;
}
public static Object calculate(String exp) throws Exception {
exp = parseExpress(exp);
ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByName("js");
return engine.eval(exp);
}
public static void main(String... a) throws Exception {
Object result = calculate("10*2*40%*34/3");
System.out.println("结果:" + result + " ; 类型:" + result.getClass().getName());
}
}