package trees.expressiontrees; /** * This abstract class represents the nodes in an expression tree. */ public abstract class ExpressionNode { Token t; abstract double value(); // Return the value of this node. } /** * Class to represent node holding an integer. */ class NumbNode extends ExpressionNode { int number; // The number in the node. NumbNode(Operand op) { number = op.value(); } double value() { return number; } } /** * Class to represent node holding an operation. */ class BinaryOpNode extends ExpressionNode { char op; // The operator. ExpressionNode left; // The left operand. ExpressionNode right; // The right operand. BinaryOpNode(Operation op, ExpressionNode left, ExpressionNode right) { this.op = op.toString().charAt(0); this.left = left; this.right = right; } // To get the value, compute the value of the left and // right operands, and combine them with the operator. double value() { double leftValue = left.value(); double rightValue = right.value(); switch ( op ) { case '+': return leftValue + rightValue; case '-': return leftValue - rightValue; case '*': return leftValue * rightValue; case '/': return leftValue / rightValue; default: return Double.NaN; // Bad operator. } } }