Created
October 3, 2015 14:36
-
-
Save gabicavalcante/8dd2a910f047dcc11019 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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