Loading...
Loading...
Some calculators take an expression in postfix form: the operator comes after its two numbers. For example 3 4 + 2 * means (3 + 4) × 2 = 14.
To evaluate it, go through the tokens from left to right. Push each number onto a stack. For an operator + - * /, pop the top value b, then the next value a, and push a op b (integer division for /). At the end exactly one value must be left: print it.
Print one error instead of the result, for the first problem met:
Error: bad token <t> if a token is not a whole number or an operator,Error: not enough operands if an operator finds fewer than 2 values,Error: division by zero,Error: too many values if more than one value is left at the end.Use a long[] as the stack, and let Java's own exceptions report the first three problems.
long-7; a lone - is the operatorExample 1
Input
3 4 + 2 *
Output
14
3 + 4 = 7, then 7 × 2 = 14.
Example 2
Input
4 0 /
Output
Error: division by zero
Example 3
Input
2 +
Output
Error: not enough operands
The + finds only one value.
Try the problem first. Open one hint at a time.
Keep long[] stack = new long[tokens.length] and an int top, the number of values on the stack.
For an operator, read stack[top - 1] and stack[top - 2]: with fewer than 2 values, one index is -1 and Java throws ArrayIndexOutOfBoundsException.
Remember the current token in a variable declared before the try, so the catch for NumberFormatException can print it.
After the loop, throw IllegalArgumentException("too many values") when top is not 1.
Write your Java code, run it on the examples and submit it to hidden tests.
Solve in the editor