Java Expression Parser & Calculator Shunting Yard Algorithm

前端 未结 4 1233
一个人的身影
一个人的身影 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条回答
  •  死守一世寂寞
    2021-01-23 20:06

    Couldn't you use the javascript scripting engine? (you would need a bit of tweaking for the 5--2 expression) The code below outputs:

    3+2*1-6/3 = 3.0
    3++2 = Invalid Expression
    -5+2 = -3.0
    5--2 = 7.0
    

    Code:

    public class Test1 {
    
        static ScriptEngine engine;
    
        public static void main(String[] args) throws Exception {
            engine = new ScriptEngineManager().getEngineByName("JavaScript");
    
            printValue("3+2*1-6/3");
            printValue("3++2");
            printValue("-5+2");
            printValue("5--2");
        }
    
        private static void printValue(String expression) {
            String adjustedExpression = expression.replaceAll("--", "- -");
            try {
                System.out.println(expression + " = " + engine.eval(adjustedExpression));
            } catch (ScriptException e) {
                System.out.println(expression + " = Invalid Expression");
            }
        }
    }
    

提交回复
热议问题