Loading...
Loading...
Build a calculator whose operations are enum constants. enum Operation has a private final symbol and abstract long apply(long a, long b), with a body for PLUS("+"), MINUS("-"), TIMES("*"), DIVIDE("/") and MODULO("%"). A static fromSymbol(String s) throws IllegalArgumentException for an unknown symbol, and DIVIDE and MODULO throw ArithmeticException when b is 0.
Evaluate each line.
a op b, separated by spaces.a op b = result, a op b = ERROR: divide by zero, or UNKNOWN OPERATOR op.Example
Input
4 12 + 4 7 % 0 9 ^ 2 -17 / 5
Output
12 + 4 = 16 7 % 0 = ERROR: divide by zero UNKNOWN OPERATOR ^ -17 / 5 = -3
Java division rounds toward zero, so -17 / 5 is -3.
Try the problem first. Open one hint at a time.
fromSymbol loops over values() and compares op.symbol.equals(s).
Two catch blocks: IllegalArgumentException for the symbol and ArithmeticException for the division.
Throw the ArithmeticException yourself when b is 0, so the message is under your control.
Write your Java code, run it on the examples and submit it to hidden tests.
Solve in the editor