Calculator State Diagram

The following state diagram [pdf] contains 8 states and shows the buttons that are recognized from each state. The initial state is ZERO_FIRST. Note that Clear isn't shown, since it should have the same behavior whenever it is pressed.

Although this looks complicated, by maintaining a state variable and performing switch statements for each type of event (digit, decimal, binary operator, etc.), the logic is relatively straightforward to implement.

A good way to start is to define an enumeration for these states:

public enum State
{
    ZERO_FIRST,
    ZERO_INTERMED,
    OPERAND_FIRST_NODEC,
    OPERAND_FIRST_DEC,
    OPERAND_INTERMED_NODEC,
    OPERAND_INTERMED_DEC,
    AFTER_EQUALS,
    OPERATOR
}

and keep an instance variable holding the current state:

private State state;

Imagine how convoluted the logic might become if we hadn't first developed such a precise state diagram!