Shorter solution to if,else if,else if

前端 未结 6 1840
深忆病人
深忆病人 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:43

    Here's a snippet:

    public static void main(String[] args) {
    
            float primeResult;
            String exp = "4-2";
            int i = 1;
            ScriptEngineManager mgr = new ScriptEngineManager();
            ScriptEngine engine = mgr.getEngineByName("JavaScript");
    
            char[] myVar = new char[] { '*', '/', '-', '+' };
    
            for (int myVarCtr = 0; myVarCtr < myVar.length; myVarCtr++) {
    
                if (exp.charAt(i) == myVar[myVarCtr]) {
    
                    try {
                        primeResult = Float.parseFloat(engine.eval(
                                (Integer.parseInt(exp.substring(0, i)))
                                        + Character.toString(myVar[myVarCtr])
                                        + (Integer.parseInt(exp.substring(i + 1,
                                                exp.length())))).toString());
                        System.out.println(primeResult);
                    } catch (ScriptException e) {
                        e.printStackTrace();
                    }
    
                }
    
            }
        }
    

提交回复
热议问题