Loading...
Loading...
A shop counter calculator keeps one running value that starts at 0 and has an undo key that goes back one step.
Write a class Calculator with a field value and methods for add, sub, mul, div, clear and undo. undo restores the value from before the last successful operation; it remembers only one step, so a second undo in a row does nothing. Division by zero prints a message and changes nothing.
add x, sub x, mul x, div x, clear, undo or show.show, the current value on its own line. For div 0, the line CANNOT DIVIDE BY ZERO. Other commands print nothing./ does itExample
Input
7 add 10 mul 5 show undo show div 0 show
Output
50 10 CANNOT DIVIDE BY ZERO 10
10 × 5 = 50, undo goes back to 10, and dividing by zero is refused.
Try the problem first. Open one hint at a time.
Keep two more fields: previous and a boolean canUndo.
Every successful operation first copies value into previous and sets canUndo to true.
undo copies previous back and sets canUndo to false.
Write your Java code, run it on the examples and submit it to hidden tests.
Solve in the editor