Java Expression Parser & Calculator Shunting Yard Algorithm

前端 未结 4 1203
一个人的身影
一个人的身影 2021-01-23 19:29

So the task is to create our own parser for a expression calculator. For Example:

Input: 3+2*1-6/3 Output: 3

Input: 3++2 Output: Invalid Expression

Input

4条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-01-23 19:57

    Here you are:

    private static final ScriptEngine engine = new ScriptEngineManager().getEngineByName("JavaScript");
    
    public static String eval(String matlab_expression){
        if(matlab_expression == null){
            return "NULL";
        }
        String js_parsable_expression = matlab_expression
                .replaceAll("\\((\\-?\\d+)\\)\\^(\\-?\\d+)", "(Math.pow($1,$2))")
                .replaceAll("(\\d+)\\^(\\-?\\d+)", "Math.pow($1,$2)");
        try{
            return engine.eval(js_parsable_expression).toString();
        }catch(javax.script.ScriptException e1){
            return null; // Invalid Expression
        }
    }
    

提交回复
热议问题