CSCI 136: Assignment 6 -- Calculator

Due 4/14/97


Your next program is to implement a calculator applet. The calculator should take expressions input in postorder and display the results of the computation. Thus to calculate 3+5, click on 3, enter, 5, +. The answer should then be displayed. To calculate 3+5*7, click on 3, enter, 5, enter, 7, *, +. Try these on the calculator below:



Aside from the main applet, the program includes three classes: State, DigitButton, and OpButton. A state object represents the memory of the calculator. Its purpose is to keep track of the current state of the computation. For instance, it has to keep track of whether the user is entering a number, and what the number is so far. It also must keep track of the stack used in the computation. DigitButton and OpButton represent "smart" buttons which represent digits and operations, respectively. When the user clicks on a DigitButton, it is responsible for informing the state what number has been clicked on so the state can use it to build the number being typed in. When the user clicks on an OpButton, the button informs the state what operation is to be performed next so that the state can perform the operation.

Remember that when the user clicks on an object, that object is first given the opportunity to handle the event. If it doesn't know how, the event is passed up to the object containing the original object, and so forth until either an object knows how to handle the event or it is discarded. Thus our "smart" buttons can (and should) handle any mouse click on them.

Notice that we only create "smart" buttons for digits and operations. This is because there are several buttons of each kind. The "unique" buttons: Enter, pop, and clear, are handled directly by the applet. They simply send a message to the state corresponding to the operation.

Your job is to fill in the missing details for the classes State, DigitButton, and OpButton. You might find it easier to write the code first under the assumption that the user must push the "enter" button after punching in each number. However, for full credit, it should also handle the case where the user punches in a number followed immediately by an operation. The result should be equivalent to sticking in an intervening "enter". That is punching in 5, enter, 7, + should give the same results as 5, enter, 7, enter, +.