Expr4JJava的表达式计算引擎
Expr4J 是一个Java的表达式计算引擎,可以用来计算例如在 Excel 单元格中的表达式等。
示例代码:
package org.boris.expr.util;
import java.io.*;
import org.boris.expr.*;
import org.boris.expr.parser.ExprParser;
public class ExprEvaluator
{
public static void main(String[] args) throws Exception {
SimpleEvaluationContext context = new SimpleEvaluationContext();
System.out.println("Expr Evaluator v1.0");
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
while (true) {
try {
System.out.print(">");
String line = br.readLine();
if (line == null)
break;
Expr e = ExprParser.parse(line);
Exprs.toUpperCase(e);
if (e instanceof ExprEvaluatable) {
e = ((ExprEvaluatable) e).evaluate(context);
}
System.out.println(e);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
package org.boris.expr.util;
import org.boris.expr.BasicEngineProvider;
import org.boris.expr.engine.DependencyEngine;
import org.boris.expr.engine.Range;
public class DependencyExample
{
public static void main(String[] args) throws Exception {
DependencyEngine e = new DependencyEngine(new BasicEngineProvider());
e.set("B1", "=A1*2");
e.set("A1", "=12*2");
e.set("C1", "=B1*A1");
System.out.println(e.getValue(Range.valueOf("B1")));
System.out.println(e.getValue(Range.valueOf("C1")));
e.set("A1", "2");
System.out.println(e.getValue(Range.valueOf("B1")));
System.out.println(e.getValue(Range.valueOf("C1")));
}
}
评论