Skip to content

Instantly share code, notes, and snippets.

@gabicavalcante
Created October 3, 2015 14:36
Show Gist options
  • Save gabicavalcante/8dd2a910f047dcc11019 to your computer and use it in GitHub Desktop.
Save gabicavalcante/8dd2a910f047dcc11019 to your computer and use it in GitHub Desktop.
/**
* Return the value of the expression
*/
public double eval() throws NumberFormatException {
if (this.isLeaf()) return Double.parseDouble(this.data());
Double left = ((ExpressionTree) this.left()).eval();
Double right = ((ExpressionTree) this.right()).eval();
return eval(this.data(), left, right);
}
/**
* Return the value of 'x op y'
* where 'op' is "+", "*", "/" or "^"
*/
private double eval(String op, double x, double y) {
switch (op) {
case "+":
return x + y;
case "-":
return x - y;
case "*":
return x * y;
case "/":
return x / y;
case "^":
return Math.pow(x, y);
default:
break;
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment