Calculator has two main components:
- Display:
- Keys:
- Numbers (0-9)
- Operators (+, -, *, /)
- Decimal
- Equals
- Clear
Add a listener that will listen to the keys when pressed and will recognize the key type.
Consider what an average person would do when they use a calculator. They can press any of the following keys:
- A number key (0-9)
- An operator key (+, -, *, /)
- The decimal key
- The equal key
- The clear key
- If 0 (the default number) is shown, replace it with the target number.
- If non-zero number is shown, append the target number to it.
- If decimal is pressed, it should display.
- If a number is pressed after a decimal key, it should be appended on the display as well.
- If operator key is pressed, highlight the button so the user will know which operation will be executed.
- Release the operator key from its pressed state.
- Replace previous number with new number.
- Calculate result of:
- The first number entered
- The operator
- The second number entered
- Replace displayed value with the result.
- All Clear (denoted
AC
) clears everything and resets the calculator to its initial state. - Clear Entry (denoted
CE
) clears the current entry. It keeps previous numbers in memory.
- If the decimal is already displayed, then nothing should happen if the decimal key is pressed.
- If the decimal key is pressed after an operator key, then the display should show
0.
.
- If an operator key is pressed, it should light up
- Nothing should happen if the same operator key is pressed multiple times.
- If another operator key is pressed after the first one, the first should be released and second one pressed.
- If a number key is pressed, followed by an operator, a number, and another operator, the display should be updated with the new calculated value.
- Nothing should happen if the equals key is pressed before any operator has been pressed.
- If a number has been pressed, followed by an operator, and then the equals key, the calculator should repeat the operation on the number itself.
- If the equals key is pressed after a calculation, another calculation should be able to be performed subsequently (chaining multiple operations).
- If a decimal or number key is pressed after the equals key, the display should be replaced with
0.
or the number respectively. - If an operator key is pressed right after the equals key, there should not be any calculations.
- If any key is pressed (except clear),
AC
should be changed toCE
. - If
CE
is pressed, the display should read 0, andCE
should be reverted toAC
as its initial state. - If
AC
is pressed, reset the calculator to its initial state.