Writing the Calculator Script Program

The calculator script program is relatively straightforward. As buttons on the calculator’s keypad are clicked, data is entered into the display register or a task is processed. When one of the keys from 0 to 9 is clicked, the digit is appended to the Display text box. Listing 13.12 shows the code run when the numeral 1 key is clicked.

Listing 13.12: Press1 Script Routine in Programmable Calculator

‘Key:          1
Sub Press1()
Display.Text = Display.Text & “1”
End Sub

Clicking the plus (+) key causes the code in Listing 13.13 to be run. The code executes the PressEquals routine if a mathematical operator was saved in OpRegister. Then it saves the current mathematical operator in OpRegister. It also saves the Display register in the XRegister before clearing the Display register. The code for the other mathematical operators (–, *, and /) works in the same way.

Listing 13.13: PressAdd Script Routine in Programmable Calculator

‘Key:          +
Sub PressAdd()
If Len(OpRegister.Text) > 0 then
   PressEquals
End If
OpRegister.Text = “+”
XRegister.Text = Display.Text
Display.Text = “”
End Sub

Pressing the equal sign (=) completes the calculation process and displays the results. As shown in Listing 13.14, the code selects the appropriate mathematical operation and performs it based on the current value of OpRegister. The result is saved in the Display register, and the XRegister and the OpRegister are both cleared at the end of this routine.

Listing 13.14: PressEquals Script Routine in Programmable Calculator

‘Key:          =
Sub PressEquals()
Select Case OpRegister.Text
Case “+”
   Display.Text = FormatNumber(CDbl(XRegister.text) + CDbl(Display.Text))
Case “-”
   Display.Text = FormatNumber(CDbl(XRegister.Text) - CDbl(Display.Text))
Case “*”
   Display.Text = FormatNumber(CDbl(XRegister.Text) * CDbl(Display.Text))
Case “/”
   Display.Text = FormatNumber(CDbl(XRegister.Text) / CDbl(Display.Text))
End Select
XRegister.Text = “”
OpRegister.Text = “”
End Sub

© 1998 SYBEX Inc. All rights reserved.