Here is one way to do it. This code is written in Java. Note that it does not handle negative numbers right now, but you can add this.
public class ExpressionParser { public double eval(String exp, Map<String, Double> vars){ int bracketCounter = 0; int operatorIndex = -1; for(int i=0; i<exp.length(); i++){ char c = exp.charAt(i); if(c == '(') bracketCounter++; else if(c == ')') bracketCounter--; else if((c == '+' || c == '-') && bracketCounter == 0){ operatorIndex = i; break; } else if((c == '*' || c == '/') && bracketCounter == 0 && operatorIndex < 0){ operatorIndex = i; } } if(operatorIndex < 0){ exp = exp.trim(); if(exp.charAt(0) == '(' && exp.charAt(exp.length()-1) == ')') return eval(exp.substring(1, exp.length()-1), vars); else if(vars.containsKey(exp)) return vars.get(exp); else return Double.parseDouble(exp); } else{ switch(exp.charAt(operatorIndex)){ case '+': return eval(exp.substring(0, operatorIndex), vars) + eval(exp.substring(operatorIndex+1), vars); case '-': return eval(exp.substring(0, operatorIndex), vars) - eval(exp.substring(operatorIndex+1), vars); case '*': return eval(exp.substring(0, operatorIndex), vars) * eval(exp.substring(operatorIndex+1), vars); case '/': return eval(exp.substring(0, operatorIndex), vars) / eval(exp.substring(operatorIndex+1), vars); } } return 0; }
}
You need to import java.util.Map.
Here is how I use this code:
ExpressionParser p = new ExpressionParser(); Map vars = new HashMap<String, Double>(); vars.put("x", 2.50); System.out.println(p.eval(" 5 + 6 * x - 1", vars));
user4617883
source share