Calculator

advertisement
CEE 102 – Lab 5: Computers
Fall 2002
This lab presents an introduction to some aspects of programming a
digital computer. You will use the modern programming language
VISUAL BASIC in these exercises. The VISUAL BASIC language is
embedded in most of the Microsoft Office Products including WORD,
EXCEL, and POWER POINT. The language is event-driven and it has
a graphical interface that allows the user to create a professionallooking interactive program. (In fact Microsoft Office is written in
VISUAL BASIC and its companion language VISUAL C++.)
Information is entered and choices are implemented using a variety of
program elements including textboxes (in which one types a message or
number), and buttons, sliders, pull-down menus, and knobs (which are
activated by the mouse). Text and numeric output data is displayed in
textboxes or by means of a variety of display elements including dial or
bar indicators and graphs (for numeric data), and lights (for digital
[true/false] data).
Your first task will be to record a MACRO program using the MACRO
RECORD feature in WORD. This feature automatically generates code
in VISUAL BASIC that will duplicate your actions when played back,
including typing, drawing, or selection of one or many menu items. You
will examine the VISUAL BASIC code that you created and then
modify it. You will then test your modified code. In a later task you will
build upon existing program fragments to develop a four function
calculator (ADD, SUBTRACT, MULTIPLY, and DIVIDE). There are
also optional tasks of adding to a graphical template to assist in the
evaluation of the traction formula associated with the automobile, as
well as a task to create an interactive encoder/decoder for converting
text to Morse code and back.
You are to split into teams of two, with one person taking the lead on a
given task while the other person helps. After completing a task your
TA will record the name of the lead programmer – you should then
switch roles.
BE AWARE: You will have to think about some of the steps in this lab –
the procedures do not always give step-by-step directions but instead
give you tools to use and tell you what needs to be done.
Task 1 & 2: Recording a Macro
In this task you will be recording two macros that will write your name and address when
the macros are run.
Task 1 is a simple exercise to make you more familiar with macros and demonstrate how
visual basic code is written.
1. Open a new Word document and save in your TA’s folder on the desktop –
save as “(Your name)_Address”.
2. Go to the Menu “Tools: Macro: Record New Macro…”
3. Type “Test_Name” for the Macro Name.
4. Under “Store Macro In” Select your document name. This tells it whether to
save this macro in Word or just with this document.
5. “Assign Macro To” allows you to create a button in the toolbar or a hotkey on
the keyboard to run the macro. Select “Toolbar”.
6. Under the "Commands" tab, the right column should contain your macro
name. Drag this name up to the toolbar and release. Right click on the new
toolbar button and rename the button and assign a “Button Image”.
7. Return to the "Customize" window, make sure the "Save In" bar at the bottom
refers to your document (NOT Normal.dot), and Select "Close".
8. Now you are recording a macro and every click and keystroke is being
recorded.
9. Type the following: "(Your first name)", press Enter, "(Your middle name)",
press Enter, select the BOLD button in the toolbar, "(Your last name)",
deselect the BOLD button, press enter). Hit the stop button (the square in the
small window) to stop recording. (You may also go to the Macro menu to stop
recording)
10. Notice that every time you select your Test_Name macro button in the toolbar
your name as you typed it will appear.
11. Now go to the menu “Tools: Macro: Macros…” (Notice that you can also
press Alt+F8).
12. Highlight your Test_Name Macro with a single click and select the “Edit”
button. Your visual basic code should be displayed. Take a look at this code.
The programs you will later write will use this same language.
13. Find your middle name and shorten it to an initial with a period after it. Go to
“File: Close and Return to Microsoft Word”. Select your macro button and
verify that the change was made.
Task 2 – Create an address label
1. Clear the text in your document and record a macro titled “MyAddress”
(Same as steps 1-7 above – Make sure it saves the macro in your document
and NOT Normal.dot )
2. Instead of typing the information directly into the document, create a text box
by going to “Insert: Text Box” (once it is selected, click and drag to the
desired size – you can change this later).
3. Type your address in the text box. Highlight the box or text and format your
text - choose a color, size, font, etc. (Try out a few different ones before you
select a combination you like). For now leave the border around the box.
4. Once you have it the way you like stop recording. Clear the text box that you
just created and press the Address button to verify that it works.
5. Access your code (steps 11-12 above) and remove any needless steps (did you
pick a few fonts or colors before you settled on one?). If you’re not sure
whether something can be removed ask your TA.
6. Once completed save your document and demonstrate to your TA that the
program works (you may need to show your code).
Note: If you would like to use this at a later time you may want to add additional
steps to your recorded macro. To format the text box (eliminate or change border,
get an exact position, allow text wrapping, etc) right click on the border of the text
box and select “Format Text Box…”
Task 3: Calculator
Part1. Exploring existing code for an adding calculator, modify program to switch
its function from addition to subtraction
1. Open the file named calc_2001.doc
2. Save the file as “calc-pt1_Your name.doc” in your lab section’s folder on the Desktop
(click on File:SaveAs)
3. Left-click on the “Calculator” button. A new window will appear.
4. Click on the top text box (known as TextBox1) and type in a number
5. Repeat this for the second text box (TextBox2), and observe that the sum is displayed
in the third box (TextBox3).
6. Click on the bottom button to record your results into the Word document
7. Go to Tools:Macro:Macros… to open the macros menu
8. Highlight the “Calculator” macro from the list and click on “Edit”
9. The Visual Basic code for the Calculator function will appear.
10. Locate the Calculator() subroutine, and identify the UserForm number for this
subroutine
11. Under the “Project” window, double-click the appropriate UserForm number.
12. The calculator will appear on your screen in an editable form. You can edit
TextBox1 and TextBox2 in the calculator by double clicking the item you want to
edit. (try it) – Note that the code in TextBox1_Change() should read,
TextBox3.Text= Val(Textbox1.Text) + Val(TextBox2.Text). This line of code is
executed whenever the TextBox1 is changed. Think back to when you ran the
calculator. You should have noted that as soon as the value of the TextBox1 or
TextBox2 was changed the result appeared in TextBox3.
13. Edit the code for the calculator so that it now subtracts two numbers, rather than
adding them together. (You must modify the code in both the TextBox1_Change()
and the TextBox2_Change() routines.) – also change the + symbol on the user form to
a -.
14. Go to File:Quit and Return to Microsoft Word. Now test the new calculator to see if
it works.
15. Once completed save your document and demonstrate to your TA that the program
works (you may need to show your code).
Part2. Modifying for +/In part 2, you will modify the calculator so it can perform addition AND subtraction.
First, you will create a keypad for inputting the numbers 0 – 9.
1. Open the file named “calc_2001.doc.”
2. Save the file as “calc-pt2_YourName.doc” in your lab section’s folder on the Desktop
(click on File:SaveAs).
3. Click on Tools:Macro:Macros… (or hit Alt-F8)
4. Highlight the “Calculator” macro from the list and click on “Edit.”
5. Open the Calculator’s UserForm.
6. Resize calculator window – Make it bigger to accommodate a keypad.
7. From the “toolbox” menu, drag a new CommandButton onto the calculator.
8. Click on the new button, and rename it from “CommandButton2” to “1”.
9. Now double-click the new button to view its VB code.
10. Beneath the CommandButton2_Click() header, add the following line:
TextBox1.Text = TextBox1.Text + "1"
11. This will append the number 1 to the contents of TextBox1.
Notice that by putting quotation marks around the “1”, the function will APPEND
the number 1 to the end of the existing value in the TextBox. This is known as a
string or text operation. If you wanted to add two numbers together such as the
value of TextBox1.Text and the value 1, you would have to remove the quotation
marks, and place the TextBox reference within the parentheses of Val().
Eg. TextBox1.Text = val(TextBox1.Text) + 1
The concept of DATA TYPE (for example, string or numeric) can be a confusing
aspect of computer programs.
Notice also that the form of the expression above is X = X + 1. If you view this
as an expression in algebra it is clearly wrong. X does not equal X + 1. In
computer programs however this type of form is commonplace. You should not
read the equals sign as “equals”, rather read it as “is replaced by”. Thus the
statement that X = X +1, becomes the value of X is replaced by the value of X
plus 1. So if X had the value of 23 before this statement was executed, it would
have the value of 24 after the statement is executed.
12. Hit Alt-Q to return to Word and test that the new button works properly.
13. Now repeat these steps to add buttons for the numbers 0-9 to the calculator.
14. Now you will need to remove TextBox2 from the user form by selecting it and hitting
delete on the keyboard. Delete the + symbol from the user form as well.
15. Next you will add two new buttons to perform addition and subtraction. When the
“+” button is hit, the calculator should add the value of TextBox1.Text to the value of
TextBox3.Text and place the result in TextBox3.Text. This will require the line
TextBox3.Text = Val(TextBox3.Text) + Val(TextBox1.Text) to be added to the “+”
button code. After TextBox3.Text is executed, the contents of TextBox1.Text should
be cleared with the additional instruction, TextBox1.Text = “”. Thus you will have
two lines of instructions associated with the CommandButtonx_Click() routine.
Finally, the old instruction of the TextBox1_Change() subroutine should be removed
(see note below). After doing this for the “+” button, test it. If it works, proceed to do
the same for the “-“ button. Be sure to read the below notes carefully:
NOTE: Private Sub …() is a heading, do not change the headings. Only
change the contents beneath the headings.
NOTE: When hitting the ‘+’ button, the contents of the bottom (TextBox3) and
top text box (TextBox1) should be added and the result placed in the bottom text
box. When hitting the ‘-‘ button, the top box should be subtracted from the
bottom box (don’t worry if you hit ‘5’ and ‘-‘ and ‘-5’ appears in the bottom
box; it has just computed
0–5 = -5.
16. Add another button that will clear the contents from the textboxes when selected.
17. Test that the new calculator works for both addition and subtraction.
18. Once completed save your document and demonstrate to your TA that the program
works (you may need to show your code)..
Task 4: Four-function Calculator
Jack St. Clair Kilby invented the four-function calculator as well as the microchip. You
will modify a program to develop a four-function calculator in Word.
Such a calculator will yield the following results:
Input: 1,+,2,*,3,=
Answer: 9 (1+2 = 3 ; 3*3 = 9) , NOT: 1 + (2*3) = 1 + 6 = 7
1. Open the calc_2001.doc file
2. Save the file as “inline_YourName.doc” in your lab section’s folder on the Desktop
(click on File:SaveAs).
3. Try testing the inline calculator macro. Enter 123 + 23 - 1 =. You should get 145 as
your answer.
4. Examine the code for the “inline calculator” in userform 6 (under Menu “Tools:
Macro: Macros…” – see Task 3 if you don’t recall how to do this). Get a handout
copy of this code from your TA.
5. Note in the handout that there are 2 different data types used in this application –
integers and strings. A string is a collection of symbols – letters, numbers,etc.
“Accumulator”, “LastOP”, and “var” are variables that are used in the program.
“Accumulator” and “LastOP” are integers. “Var” is a string variable.
6. Note again that the value of ‘accumulator’ in many of the command buttons is
updated using a basic structure like “a = a + 1”. This line is meaningless in algebra
but it is common in computer programs. Read the equals sign as “is replaced by”.
Thus a = a + 1 means the NEW value of a is the OLD value of a plus 1. This
structure is used to add new digits to the display in TextBox1.Text.
7. Note also that in several subroutines a conditional statement (IF; THEN; END IF) is
used to make a check.
Data types, expressions, and conditionals are basic building blocks of modern computer
programs.
In order to understand how the calculator works let’s look at a simple example: 1 + 2 = 3
When the ‘=’ is pressed, the computation is performed and the answer is displayed in the
Textbox. Look at the code for the ‘=’ command button subroutine. Notice that the
subroutine uses If Then statements to determine the operation that is to be performed (If
LastOP=1 then do addition, if LastOP=2 then subtraction; LastOP stands for Last
Operation). Therefore, the subroutine needs to know what LastOP is – i.e., which
operation is to be performed (+,-, etc.). Now take a look at the subroutine for the plus
command button. Note that LastOP leaves the subroutine with a value of 1, therefore,
when the ‘=’ button is pressed it knows to do addition.
One last note, the ‘plus’ and ‘minus’ subroutines also have the series of If-Then
statements. This displays the answer as you go along: load the inlinecalculator and enter
3,+,3,+,3,= and notice that 6 (3+3) appears and then 9 (6+3).
8. Your task is to complete the calculator so that it carries out the additional functions of
multiplication and division. To accomplish this you will need to complete the
number pad, add new command buttons for multiply and divide, and add IF Then
statements to the subroutines for the four functions (+ , - , * , /) and the subroutine for
“=”.
9. Once completed save your document and demonstrate to your TA that the program
works (you may need to show your code).
Task 5: Traction Force Macro (optional)
1. Use your “inline_YourName.doc” in your lab section’s folder on the Desktop .
2. Left click on the Traction macro. This macro will calculate the required traction
force that a car must produce to travel a certain velocity.
3. Determine the required traction force for a 2000 lb. car with a frontal area of 20 sq. ft
traveling 50 mph up a 5 degree slope (Recall: there are 2 radians in 360). Verify
these results. If you’re not sure what to enter, look at the code!
4. Add a textbox below the traction force textbox that will show the required traction
power for a certain traction force and velocity.
5. Once completed save your document and demonstrate to your TA that the program
works (you may need to show your code).
If you would like a challenge you can try out Task 6…
Task 6: Encoding and Decoding (optional)
Part1. Converting a word to Morse code
In Task 6, you will use a typical programming structure called a “look-up table” to
convert a word to morse code.
1. Open the file named “morse.doc.” in the “good programming files” folder on the
desktop
2. Save the file as “morse-pt1_YourName.doc” in your lab section’s folder in My
Documents (click on File:SaveAs).
3. Left-click on the “Encode” button. A new window will appear.
4. Click on the first text box and type a message (can include lowercase letters,
numbers, spaces and periods).
5. Observe that the english text appears in the text box to the right and the coded
message appears in the Word document. What happens when you type a character
not included in the list in step 4?
6. Go to Tools:Macro:Macros… to open the macros menu
7. Highlight the “Encode” macro from the list and click on “Edit”
8. The Visual Basic code for the encoder function will appear.
9. Locate the Encode() subroutine, and identify the UserForm number for this
subroutine
10. Under the “Project” window, double-click the appropriate UserForm number.
11. The encoder will appear on your screen in an editable form. Double click on the left
text box to see the code. Study this code to determine how the encoding is done.
Identify the look-up table from which the conversion is made. You may not
understand all the code but just try to figure out the basic steps being taken. If you
have questions, ask your AI.
12. When you are comfortable with the code, select File -> Close and return to Microsoft
Word.
13. Now place the cursor at the beginning of the morse code message and click on the
“get char” macro button. Click on “next” and “previous” to observe what the macro
does. Again, access the code for this macro and UserForm to get a feel for the steps
involved. You will use a combination of the “Encode” and “Get char” macros in the
next part.
Part. 2 – Creating a decoder
In this part, you will create a new macro that decodes the encrypted (morse code)
message.
1. Go to the Menu “Tools: Macro: Macros…
2. You should see a macro called “Decoder”. This is an “empty” macro that has been
created for you.
3. First you should create a button on the toolbar to access this macro. Go to
Tools:Customize… and click on the Commands tab. At the bottom of the window,
make sure the SaveIn box says the name of your document. Scroll down in the
Categories window and click on Macros. You should see the name of the decode
macro appear in the Commands Window. Click and drag the macro to the toolbar
that includes “GetChar” and “Encode”.
4. Close the Customize window.
5. Now you need to create the code and the userForm for the Decode macro
6. Follow steps 6-8 from part 1, above, (with appropriate changes) to access the code for
the Decode macro. UserForm6 is a blank userForm that has been created for you.
You should modify the code for the Decode macro so that it accesses this form.
7. You are now going to design userForm6 and write the code so that it reads the morse
code characters to the right of the cursor and translates them to English.
8. In the Projects window, double-click on userForm6 and create a form similar to the
one for getChar. Your form should only have a single button, however, and should
have two text boxes (one for displaying the selected morse code character and one for
writing out the decoded (English) word.
9. Once you’ve finished making the form, double-click on the button to see the code.
You should see a window with a lot of green text appear. This is basically an outline
of the code you need to write. You should follow this outline, filling it in with the
appropriate commands.
10. To simplify the process, you should refer to the code for userForms 3 and 5 (the
Encode form and the Get Char form). You can also cut and paste in key parts of the
code from both of these forms.
11. Note that the program will have to be able to identify when it has reached the end of a
coded letter. (Hint: a space in this programming language is identified as “ “). What
should happen to textacc once the end of a coded letter is reached and the contents of
textacc is translated to English?
12. Go back to the main word document, place your cursor at the beginning of a morsecode message, and try out your program. If it doesn’t work, go back to your code and
systematically try to find where you might have made a mistake.
Download