写一个方法 传入一个字符串比如:3+2*5-4/2 返回11:
import java.util.Scanner;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
/**
* String calculate function class.
* @author frank
* @since 11/18/2010
* */
public class Test {
public static void main(String[] args) throws Exception {
System.out.println("Input your expression now:");
Scanner sc=new Scanner(System.in);
String myString=sc.next();
ScriptEngine jse = new ScriptEngineManager().getEngineByName("JavaScript");
double res = (Double)jse.eval(myString);
System.out.println(res);
}
}
用java字符串去处理很复杂的逻辑,很多细节要考虑。但是用Java去调用JS提供的eval()方法那就相当easy了。