Shorter solution to if,else if,else if

前端 未结 6 1845
深忆病人
深忆病人 2021-01-06 08:58

I\'m looking for a way to shorten this code up and avoid repeating code and if statements. What I\'m doing is creating a calculator that searches strings for operators &quo

6条回答
  •  天涯浪人
    2021-01-06 09:53

    There's no need of switch statements and complex hierrachies of classes.

    In order to simplify and shorten your code and calculate simple and complex expressions (represented as String objects), you can use the Java's JavaScript API and it's ScriptEngine class, which basically simulates a JavaScript console.

    import javax.script.ScriptEngineManager;
    import javax.script.ScriptEngine;
    
    public class MyClass{
        public static void main(String[] args) throws Exception {
            // create a script engine manager
            ScriptEngineManager factory = new ScriptEngineManager();
            // create a JavaScript engine
            ScriptEngine engine = factory.getEngineByName("JavaScript");
            // evaluate JavaScript code from String
            System.out.println(engine.eval("(5+10)*2/3"));
        }
    }
    

    This will output: 10.0

提交回复
热议问题