Plain English Rules for a Simple Infix Expression (No Parentheses)
Plain English Rules for a Simple Infix Expression (No Parentheses)
Here is a step-by-step guide for processing a simple expression without parentheses.
Start Here: Initialize
- Create an empty operandStack for numbers.
- Create an empty operatorStack for operators.
- Read the expression tokens one by one. For each token, follow the rules below.
Rule 1: If the token is an OPERAND (a number)…
- Push it directly onto the operandStack.
Rule 2: If the token is an OPERATOR (+, -, *, /)…
- Call your reduce(operator) method.
- Inside reduce, a WHILE loop should run as long as:
- The operatorStack is not empty, AND
- The operator on top of the operatorStack has a precedence greater than or equal to the current operator’s precedence.
- Inside this WHILE loop, you should call a method like calculate() which performs one operation: it pops two operands and one operator, does the math, and pushes the result back onto the operandStack.
- Inside reduce, a WHILE loop should run as long as:
- After the reduce method is finished, push the current operator onto the operatorStack.
Rule 3: After you’ve read all the tokens… (Cleanup)
This phase is typically triggered when the user presses the “equals” button.
- WHILE the operatorStack is not empty:
- Repeatedly call your calculate() method (pop two operands, one operator, compute, and push the result).
- The final answer is the single number left in the operandStack.