Loading...
Loading...
A simple calculator reads n lines. Each line should look like a op b: two integers and one operator from + - * / %, separated by single spaces. Print the integer result of each line.
A bad line must not stop the calculator. Check in this order and print:
Error: expected a op b if the line does not have exactly 3 parts,Error: bad number if a or b is not a whole number,Error: unknown operator <op> if the operator is not one of the five,Error: division by zero if / or % has b = 0.Example 1
Input
4 12 + 30 7 / 2 9 % 0 5 ^ 2
Output
42 3 Error: division by zero Error: unknown operator ^
7 / 2 is 3 in integer division.
Example 2
Input
3 5 + x * 3 1 + 2 + 3
Output
Error: expected a op b Error: bad number Error: expected a op b
Try the problem first. Open one hint at a time.
Split each line with split(" ") and throw IllegalArgumentException("expected a op b") when there are not 3 parts.
Pick the operation with an if-else chain; in the last else, throw IllegalArgumentException("unknown operator " + op).
Catch NumberFormatException and ArithmeticException before IllegalArgumentException, and print e.getMessage() for the last one.
Write your Java code, run it on the examples and submit it to hidden tests.
Solve in the editor