Java 表达式的字符串运算出结果

首先在项目中添加或应用bsh工具包

1.官网下载:http://www.beanshell.org/download.html

2.本人的资源:http://download.csdn.net/detail/qq_30552993/9610435

 

/***
 * @param  exp 算数表达式
 * @return 根据表达式返回结果
 */
private String getRs(String exp){
    Interpreter bsh = new Interpreter();
    Number result = null;
    try {
        exp = filterExp(exp);
        result = (Number)bsh.eval(exp);
    } catch (EvalError e) {
        e.printStackTrace();
        return "算数公式错误";
    }        
    exp = result.doubleValue()+"";
    if(exp.endsWith(".0"))
        exp = exp.substring(0, exp.indexOf(".0"));
        return exp;
    }
}

 

 

 

你可能感兴趣的:(Java)