Conditions - BS in Computer Science

advertisement
Decisions and Conditions
If Statements
A powerful asset of the computer is its ability to make decisions and to take alternate courses of action based on the
outcome.
A decision made by the computer is formed as a question: is a given condition true or false? If it is true, do one
thing: if it is false, do something else.
If the sun is shining Then
go to the beach
(condition)
(action to take if condition is true)
Else
go to class
(action to take if condition is false)
End If
The logic of an If…then…Else statement in flowchart form.
Sun is shining?
False
True
Go to class
Go to beach
or
If you don’t succeed Then
try, try again
(condition)
(action)
End If
False
No success ?
True
Notice in the second example that no
action is specified if the condition is not true.
In an If statement, when the condition
is true, only the Then clause is executed. When
the condition is false, only the Else clause, if
present, is executed.
Try again
If... Then. . . Else Statement – General Form
If (condition) Then
statement (s)
[ElseIf (condition) Then
statement (s) ]
[Else
statement (s) ]
End If
A block If . . . Then . . . Else must always conclude with End If. The word Then must appear on the same line as
the If with nothing following Then (except a remark). End If and Else (if used) must appear alone on a line. The
statements under the Then and Else clauses are indented for readability and clarity.
Notice that the keyword ElseIf is all one word but that End If is two words.
If... Then. . . Else Statement – Examples
When the number of units in curUnits is less than 32, select the option button for Freshman; otherwise, make sure
the button is unselected. (See Figure below.) Remember that when an option button is selected, the Value property has
a Boolean value of True.
curUnits = Val (txtUnits.Text)
If curUnits < 32 Then
optFreshman,Value = True
[Else
optFreshman.Value = False
End If
The If statement logic in flowchart form. If the number
of units is less than 32, the Freshman option button
will be selected; otherwise, the Freshman option
False
will be deselected.
Turn Freshman
option off
Units < 32?
True
Turn Freshman
option on
Flowcharting If Statements
A flowchart is a useful tool for showing the logic of an If statement. It has been said that one picture is worth a
thousand words. Many programmers find that a flowchart helps them organize their thoughts and design projects more
quickly.
The symbols used in this text are a subset of the available flowcharting symbols. The diamond-shape symbol (called a
decision symbol) represents a condition. The two branches from the symbol indicate which path to take when the
condition evaluates True or False. (See figure below.)
Tip: Always take the time to indent properly as you enter an If statement. You will save yourself debugging
time; the indentation helps to visualize the intended logic.
Conditions
The test in an If statement is based on a condition. To form condition, six relational operators (see table below) are
used to compare values. The result of the comparison is either True or False.
the flowcharting symbols used for
program decision and processes.
Decision
False
Process
True
Process
The six relational operators
Symbol
>
Relation Tested
greater than
<
less than
=
equal to
<>
not equal to
>=
greater than or
equal to
less than or equal to
<=
Examples
Val (txtAmount.Text) > mcurLimit
frmMain.Height > mcurSize
Val (txtSales.Text) < 10000
txtname.Text <strName
txtPassword.Text = “101”
optButton1.Value = True
optButton1.Value <> True
txtPassword.Text <> “101”
Val (lblCorrect.Caption) >= 1000
frmMain.Height >= 500
txtName1.Text <= txtName2.Text
The conditions to be tested can be formed with numeric variables and constants, string variables and
constants, object properties, and arithmetic expressions. However, it is important to note that comparisons
must be made on like types; that is, strings can be compared only to other strings, and numeric values can be
compared only to other numeric values, whether a variable, constant, property, or arithmetic expressions.
Comparing Numeric Variables and Constants
When numeric values are involved in a test, an algebraic comparison is made; that is, the sign of the number is taken
into account. Therefore, negative 20 is less than 10, and negative 2 is less than negative 1.
Even though an equal sign (=) means replacement in an assignment statement, in a relation test the equal sign is used
to test for equality. For example, the condition
if Val (txtPrice.Text ) = curMaximum then
means “Is the current numeric value stored in txtPrice.Text equal to the value stored in curMaximum?”
Sample Comparisons
intAlpha
intBravo
intCharlie
5
4
-5
Condition
intAlpha = intBravo
intCharlie < 0
intBravo > intAlpha
intCharlie <=intBravo
intAlpha >= 5
intAlpha <>intCharlie
Evaluates
False
True
False
True
True
True
Comparing Strings
String variables can be compared to other string variables or string literals enclosed in quotation marks. The
comparison begins with the left-most character and proceeds one character at a time from left to right. As soon as a
character in one string is not equal to the corresponding character in the second string, the comparison is terminated,
and the string with the lower-ranking character is judged less than the other.
the determination of which character is less than another is based on the code used to store character internally in
the computer. The code, called the ASCII code (pronounced “ask-key”), has an established order (called the collating
sequence) for all letters, numbers, and special characters. (ASCII stands for American Standard Code for Information
Interchange.) On the Table next page, A is less than B, L is greater than K, and all numeric digits are less than all letters.
Some special symbols are lower than the numbers, some are higher, and the blank space is lower than the rest of the
characters shown.
The ASCII collating sequence
ASCII
Code Character
Space (Blank)
32
!
33
“
34
#
35
$
36
%
37
&
38
‘ (apostrophe)
39
(
40
)
41
*
42
+
43
, (comma)
44
45
.
46
/
47
0
48
1
49
2
50
ASCII
Code
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
ASCII
Character Code
3
70
4
71
5
72
6
73
7
74
8
75
9
76
:
77
;
78
<
79
=
80
>
81
?
83
@
84
A
85
B
86
C
87
D
88
E
89
txtPerson1.Text
txtPerson2.Text
JOHN
JOAN
Character
F
G
H
I
J
K
L
M
N
0
P
Q
S
T
U
V
W
X
Y
ASCII
Code
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
ASCII
Character Code
Z
109
[
110
\
111
]
112
^
113
_
114
‘
115
a
116
b
117
c
118
d
119
e
120
f
121
g
122
h
123
i
124
j
125
k
126
l
120
Character
m
n
o
p
q
r
s
t
u
v
w
x
y
z
{
|
}
~
Del
The condition txtPerson1.Text < txtPerson2.Text evaluates False. The A in JOAN is lower ranking than the H in JOHN.
txtWord1.Text
txtWord2.Text
HOPE
HOPELESS
The condition txtWord1.Text < txtWord2.Text evaluates True. When one string is shorter than the other, it compares
as if the shorter string is padded with blanks to the right of the string, and the blank space is compared to a character in
the longer string.
lblCa1.Caption
lblCa1.Caption
300ZX
Porsche
The condition lblCar1.Caption < lblCar2.Caption evaluates True. When the number 3 is compared to the letter P,
the 3 is lower, since all numbers are lower ranking than all letters.
Feedback
intCountOne
intCountTwo
intCountThree
txtFour.Text
5
5
-3
“Bit”
Determine which conditions will evaluate True and which ones will evaluate False.
1. intCountOne >= intCountTwo
2. intCountThree < 0
3. intCountThree < intCountTwo
4. intCountOne <> intCountTwo
5. intCountOne + 2 > intCountTwo + 2
6. txtFour.Text < txtFive.Text
7. txtFour.Text <> txtFive.Text
8. txtFour.Text > “D”
9. “$” < = “?"
Testing for True or False
You can use shortcuts when testing for True or False. Visual Basic evaluates the condition in an If statement. If the
condition is a Boolean variable name, it holds the values True or False.
For example:
If blnSucessfulOperation = True Then . . .
is equivalent to
If blnSucessfulOperation Then . . .
Boolean variables hold the value 0 when False and negative 1 when True. You can actually test any variable for
True or False, Visual Basic considers any numeric variable with a value of 0 to be False; any other value will evaluate
True. The variable or expression is referred to as an implied condition.
Examples
intCounter = 10
If intCounter Then . . .
‘Evaluates True
intTotal = 0
If intTotal Then . . .
‘Evaluates False
Comparing the Text Property of Text Boxes
When you compare the Text property of a text box with another value, you must be careful. The Text property
behaves like a variant. That is, if you use it like a string, it acts like a string; but if you use it like a number, it acts like a
number. it acts like a number. However, sometimes your intentions are not clear, and sometimes you are using the Text
property as numeric, but the user enters nonnumeric data or no data at all.
Visual Basic compares one text box to another as strings and compares a text box to a numeric variable or constant
with a numeric compare. You can force a numeric comparison on a Text property by using the Val function. You should
always use the Val function on a numeric Text property when you need to compare or calculate. Remember, the Val
function converts blank values to zero.
Examples
txtFirst.Text txtSecond.Text txtFirst.Text > txtSecond.Text
+1
True
1
100
True
2
-100
False
+100
(blank)
True
0
Val (txtFirst.Text) > Val (txtSecond.Text)
False
False
True
False
Comparing Uppercase and Lowercase Characters
When comparing strings, the case of the characters is important. An uppercase Y is not equal to a lowercase y.
Because the user may type a name or word in uppercase, lowercase, or as a combination of cases, we must check all
possibilities. The easiest way is to use the string function UCase or LCase, which returns the uppercase or lowercase
equivalent of a string, respectively.
UCase and LCase – General Form
UCase (string)
LCase (string)
UCase and LCase – Examples
txtOne.Text Value
Basic
PROGRAMMING
Robert Jones
hello
UAse(txtOne.Text)
BASIC
PROGRAMMING
ROBERT JONES
HELLO
LCase(txtOne.Text)
basic
programming
Robert jones
hello
An example of a condition using the UCase function follows.
If UCase (txtOne.Text) = “BASIC” Then
‘Do something
End If
Note that when you convert txtOne.Text to uppercase, you must compare it to an uppercase literal (“BASIC”) if
you want it to evaluate as True.
Compound Conditions
You can use compound conditions to test more than one condition. Create compound conditions by joining
conditions with logical operators. The logical operators are Or, And, and Not.
Logical
Operator
Or
And
Not
Meaning
Example
If one condition or both conditions are true, the
entire condition is true.
Both conditions must be true for the entire
condition to be true.
Reverses the condition so that a true condition
will evaluate false and vice versa.
lblNumber.Caption = 1 Or _
lblNumber.Caption = 2
txtNumber.Text > 0 And _
txtNumber.Text < 10
Not lblNumber.Caption = 0
If optMale.Value = True And Val (txtAge.Text) < 21 Then
mintMinorMaleCount = mintMinorMaleCount + 1
End If
If optJunior.Value = True Or optSenior.Value = True Then
mintUpperClassmanCount = mintUpperClassmanCount + 1
End If
The first example requires that both the option button test and the age test be true for the count to be
incremented. In the second example, only one of the conditions must be true.
One caution when using compound conditions: Each side of the logical operator must be a complete condition.
For example,
optJunior.Value Or optSenior.Value = True
is incorrect.
Combining And and Or
You can create compound conditions that combine multiple And and Or conditions. When you have both an And and
Or, the And is evaluated before the Or. However, you can change the order of evaluation by using parentheses; any
condition inside parentheses will be evaluated first.
For example, will the following condition evaluate True or False? Try it with various values for curSale,
optDiscount, and txtState.Text.
If curSale > 1000 Or optDiscount.Value = True And UCase (txtState.Text) <> “CA” Then
‘(Calculate the discount)
End If
curSale
1500
1000
1000
1500
1000
optDiscount.Value
False
True
True
True
False
UCase(txtState.Text)
CA
OH
CA
NY
CA
Condition Evaluates
True
True
False
True
False
Nested If Statements
In many programs another If statement is one of the statements to be executed when a condition tests True or
False. If statements that contain additional If statements are said to be nested If statements. The following example
shows a nested If statement in which the second If occurs in the Then portion of the first If.
Flowcharting a nested If statement
intTemp > 32 ?
False
lblComment.Caption
True
intTemp > 32?
False
True
= “Freezing”
lblComment.Caption
= “Moderate”
lblComment.Caption
= “Hot”
If intTemp > 32 Then
If intTemp > 80 Then
lblComment.Caption = “Hot”
Else
lblComment.Caption = “Moderate”
End If
Else
lblComment.Caption = “Freezing”
End If
To nest If statements in the Else portion, you may use either of the following approaches; however, your code is
simpler if you use the second method (using ElseIf . . . then).
If intTemp <= 32 Then
lblComment.Caption = “Freezing”
Else
If intTemp > 80 Then
lblComment.Caption = “Hot”
Else
lblComment.Caption = “Moderate”
End If
End If
If intTemp <= 32 Then
lblComment.Caption = “Freezing”
ElseIf intTemp > 80 Then
lblComment.Caption = “Hot”
Else
lblComment.Caption = “Moderate”
End If
You may nest Ifs in both the Then and Else. In fact, you may continue to nest Ifs within Ifs as long as each If has
an End if. However, projects become very difficult to follow (and may not perform as intended) when Ifs become too
deeply nested (see figure below).
optMale.Value?
True
False
txtAge.Text < 21 ?
txtAge.Text < 21 ?
True
Add 1 to
mintMinorMaleCount
False
True
Add 1 to
mintMinorMaleCount
Add 1 to
mintMinorFemaleCount
False
Add 1 to
mintMinorFemaleCount
Tip: Indentation can help you catch errors. Visual Basic always matches on Else with the last unmatched If,
regardless of the indentation.
If optMale.Value = True Then
If Val (txtAge.Text) < 21 Then
mintMinorMaleCount = mintMinorMaleCount + 1
Else
mintMaleCount = mintMaleCount + 1
End If
Else
If Val (txtAge.Text) < 21 Then
mintMinorFemaleCount = mintMinorFemaleCount + 1
Else
mintFemaleCount = mintFemaleCount + 1
End If
End If
Feedback
Assume that intFrogs = 10, intToads = 5, and intPolliwogs = 6.
What will be displayed for each of the following statements?
1. If intFrogs > intPolliwogs Then
optFrogs.Value = True
optToads.Value = False
Else
optFrogs.Value = False
optToads.Value = True
2. If intFrogs > intToads + intPolliwogs Then
lblResult.Caption = “ti’s the frogs”
Else
lblResult.Caption = “It’s the toads and the polliwogs”
End If
3. If intPolliwogs > intToads And intFrogs <> 0 Or intToads = 0 Then
lblResult.Caption = “It’s true”
Else
lblResult.Caption = “It’s false”
End If
4. Write the statements necessary to compare txtApples.Text and txtOranges.Text. Display in lblMost.Caption
which has more, the apples or the oranges.
5. Write the Basic statements that will test the current value of curBalance. When curBalance is greater than
zero, the check box for Funds Available called chkFunds should be selected, the curBalance set back to zero,
and intCounter incremented by one. When curBalance is zero or less, chkFunds should not be selected (do
not change the value of curbalance or increment the counter).
Using If Statements with Option Buttons and Check Boxes
We have used the Click event for option buttons and check boxes to carry out the desired action. Now that you
can use If statement, you should not take action in the Click events for these controls. Instead, use If statements
to determine which options are selected.
To conform to good programming practice and make your programs consistent with standard Windows
applications, place your code in the Click event of command buttons. For example, refer to the Visual Basic Print
dialog box (see figure below); no action will occur when you click on an option button or check box. Instead,
when you click on the OK button, VB checks to see which options are selected.
The Visual basic Print dialog box. When the user
clicks OK, the program checks the state of all
option buttons and check boxes.
In an application such as the message formatter project in our previous Computer Laboratory exercise,
you could modify the code for the Display command button to include code similar to the following:
if optBlue.Value = True then
lblName.BackColor = vbBlue
ElseIf optGreen.Value = True Then
lblName.BackColor = vbGreen
Else
lblName.BackColor = vbBlack
End If
If chkFastShip.Value = Checked Then
curTotal = curTotal + curFastShipRate
End If
If chkGiftWrap.Value = Checked Then
curTotal = curTotal + curWrap
End If
A “Simple Sample”
Test your understanding of the use of the If statement by coding some short examples.
Test the Value of a Check Box
Create a small project that contains a check box, a label, and a command button. Name the command
button cmdTest, the check box chkTest, and the label lblMessage. In the Click event for cmdTEst, check
the value of the check box. If the check box is currently checked, display “Check box is checked” in
lblMessage.
Private Sub cmdTest_Click ()
‘Test the value of the check box
If chkTest.Value = Checked Then
lblMessage.Caption = “Check box is checked”
End If
Test your project. When it works, add an Else to the code that displays “Check box is not checked”.
Test the Value of Option Button
Remove the check box from the previous project and replace it with two option buttons, named
optFreshman and optSophomore and captioned “< 30 units” and “ >= 30 units”. Now change the If
statement to display “Freshman” or “Sophomore” in the label.
If optFreshma.Value = True Then
lblMessage.Caption = “Freshman”
Else
lblMessage.Caption = “Sophomore”
End If
Can you modify the sample to work for Freshman, Sophomore, Junior, and Senior? In the
sections that follow, you will see code for testing multiple option buttons and check boxes.
Checking the Value of an Option Button Group
Nested If statements work very well for determining which button of an option button group is selected. Recall
that in any group of option buttons, only one button can be selected. Assume that your form has a group of
buttons for Freshman, Sophomore, Junior, or Senior. In a calculation procedure, you want to add 1 to one of
four counter variables, depending on which option button is selected:
If optFreshman.Value = True Then
mintFreshmanCount = mintFreshmanCount + 1
ElseIf optSophomoreCount.Value = True Then
mintSophomoreCount = mintSophomoreCount + 1
ElseIf optJunior.Value = True Then
mintJuniorCount = mintJuniorCount + 1
ElseIf optSeniorCount.Value = True Then
mintSeniorCount = mintSeniorCount + 1
End If
Checking the Value of Multiple Check Boxes
Although nested If statements work very well for groups of option buttons, the same is not true for a series of
check boxes. Recall that if you have a series of check boxes, any number of the boxes may be selected. In this
situation assume that you have check boxes for Discount, Taxable, and Delivery. You will need separate If
statements for each condition.
If chkDiscount.Value = Checked Then
‘Calculate the discount
End If
If chkTaxable.Value = Checked Then
‘Calculate the tax
End If
If chkDelivery.Value = Checked Then
‘Deliver it
End If
Displaying Messages in Message Boxes
A message box is a special type of Visual Basic window in which you can display a message to the user. You can
display a message, an optional icon, a title bar caption, and command button(s) in a message box.
You may want to display a message when the user has entered invalid data or neglected to enter a required data
value. Later you will see several techniques for checking for valid input, called validating input data.
The MsgBox Statement – General Form
MsgBox “Message string” [ , Button / icon ] [ , “Caption of title bar” ]
The Message string is the message you want to appear in the message box. The Buttons portion is optional; it
determines the command buttons that will display and any icons that will appear. If you omit the Caption of title bar,
the project name will appear in the message box title bar.
The MsgBox Statement – Example
If txtName.Text = “” Then
MsgBox “Please Enter your name.”” , vbOkOnly, “Name Missing”
Selecting the MsgBox Icon
For the button/icon entry, you can choose to use the numeric values in the following table or to use the Visual Basic
constant. For example, you can display the Warning Query icon with either of these statements:
MsgBox “Let this be a warning”, vbQuestion, “Error”
or
MsgBox “Let this be a warning”, 32, “Error”
Button/Icon
OK button
Critical Message icon
Warning Query icon
Warning Message icon
Information Message icon
Value
0
16
32
48
64
Constant
vbOKOnly
vbCritical
vbQuestion
vbExclamation
vbInformation
Note: MsgBox can be used as a statement as explained here, which displays only an OK button. It can also be used as
a function. When you use MsgBox as a function, you can choose the buttons to display (such as Yes, No, Cancel: or
OK and Cancel). The function returns a value indicating which button was pressed.
Displaying a Message String
The message string you display may be a string literal enclosed in quotes or it may be a string variable. You may also
want to concatenate several items, for example, combining a literal with a value from a variable. If the message you
specify is too long for one line, Visual Basic will wrap it to the next line.
Combining Values into a Message String
You can concatenate a literal such as “Total Sales” with the value for the total sales:
Dim strMessage As String
strMessage = “Total Sales”& mcurTotalSales
MsgBox strMessage, vbOKOnly, “Sales Summary”
This example does not format the number. To remedy this condition, consider formatting the number before
concatenating it to the string.
Dim strFormattedTotal
As String
Dim strMessage
As String
strFormatttedTotal = FormatCurrency (mcurTotalSales)
strMessage = “Total Sales”& strFormattedTotal
MsgBox strMessage, vbOKOnly, “Sales Summary”
Creating Multiple Lines of Output
To display multiple lines of output, you can insert a line feed/carriage return code into the line. Use the Visual Basic
intrinsic constant vbCRLF to determine line endings. You can concatenate this constant into a message string to set
up multiple lines. This step allows you to determine the position of the line break, rather than rely on word wrap.
In this example a second line is added to the MsgBox from the previous example.
Dim strFormattedTotal
As String
Dim strMessage
As String
strFormattedTotal = FormatCurrrency (mcurTotalSales)
strFormattedAvg = FormatNumber (mcurAverageSale)
strMessage = “Total Sales”& strFormattedTotal & vbCRLF & _
“Average Sale” & strFormattedAvg
MsgBox strMessage, vbOKOnly, “Sales Summary”
Input Validation
Careful programmers check the values entered into text boxes before beginning the calculations. Validation is a
form of self-protection; it is better to reject bad data than to spend hours (and sometimes days) trying to find an
error only to discover that the problem was caused by a “user error.” Find and correcting the error early can often
keep the program from producing erroneous results or halting with a run-time error.
Checking to verify that appropriate values have been entered for a text box is called validation. The validation
may include making sure that data is numeric, checking for specific values, checking a range of values, or making
sure that required items are entered.
Checking for Numeric Values
You can make sure that data entered is truly numeric with Visual Basic’s IsNumeric function. The IsNumeric
function returns True or False to indicate the result of the value checking.
The IsNumeric Function – General Form
IsNumeric (expression)
The IsNumeric function tests whether the value is numeric and therefore can be used in a calculation. If
numeric, the result will be True; if not; the result is False. This function can help avoid problems in procedures that
contain calculation. If the data cannot be converted to a number, the calculation cannot be performed and a runtime error will occur. The only way the programmer can prevent the user from making this type of error is to check
the contents of the field after the data has been entered.
The IsNumeric Function – Exampe
If IsNumeric (txtQuantity.Text) Then
intQuantity = Val (txtQuantity.Text)
lblDue.Caption = curPrice * intQuantity
Else
MsgBox “Nonnumeric data entered.”, vbOKOnly, “Invalid Data”
End If
Checking for a Range of Values
Data validation may also include checking the reasonableness of a value. Assume you are using text box to input the
number of hours worked in a day. Even with overtime, the company does not allow more than 10 work hours in a
single day. You could check the input for reasonableness with this code:
If Val (txtHours.Text) > 10 Then
MsgBox “Too many hours entered”, vbOKOnly, “Invalid Data”
End If
Checking for a Required Field
Sometimes you need to be certain that a value has been entered into a text box before proceeding. You can
compare a text box value to an empty string literal.
If
txtName.Text <> “” Then
‘Do Something
Else
MsgBox “You must enter a value” , vbOKOnly, “Required Field”
End If
Assume that you have a text box that must have an entry and must be numeric for calculations. If you use the
Val function to convert the text to numeric and the text box is empty, what is the result? Right. Zero. If you want to
check the text box for an empty string, you must do so before using the Val function.
Incorrect:
intQuantity = Val (txtQuantity.Text)
If intQuantity = “” Then ‘Impossible Test
Correct:
If txtQuantity.Text <> “” Then
intQuantity = Val (txtQuantity.Text)
Performing Multiple Validations
When you need to validate several input fields, how many message boxes do you want to display for the user? Assume
that the user has neglected to fill in five text boxes and clicked on Calculate. You can avoid displaying five message boxes
in a row by using a nested If statement. This way you check the second value only if the first one passes, and you can exit
the processing if a problem is found with a single field.
If txtName.Text <> “ “ Then
If txtUnits.Text <> “ “ Then
If optFreshman.Value = True Or optSophomore.Value = True_
Or optJunior.Value = True Or optSenior.Value = True Then
‘Data valid – Do calculations or processing here
Else
MsgBox “Please select a Grade Level”, vbOKOnly, “Error”
End If
Else
MsgBox “Enter Number of Units”, vbOKOnly, “Error”
txtUnits.SetFocus
End If
Else
MsgBox “Please Enter Your Name”, vbOKOnly, “Error”
txtName.SetFocus
End If
Calling Event Procedures
If you wish to perform a set of instructions in more than one location, you don’t have to duplicate the code. Write the
instructions once, in an event procedure, and “call” the procedure from another procedure. When you call an event
procedure, the entire procedure is executed and then execution returns to the statement following the call.
The Call Statement (No Arguments) – General form
[ Call ] ProcedureName
Notice that the keyword Call is optional and rarely used.
The Call Statement – Examples
Call cmdCalculate_Click
cmdCalculate_Click
‘Equivalent to previous statement
In the programming example that follows, you will accumulate individual items for one customer. When that
customer’s order is complete, you need to clear the entire order and begin an order for the next customer. Refer to the
interface in Figure below; notice the two command buttons; Clear for Next Item and New Order. The command button
for next item clears the text boxes on the screen. The command button for a new order must clear the screen text boxes
and clear the subtotal fields. Rather than repeat the instruction to clear the individual screen text boxes, we can call the
event procedure for cmdClear_Click from the ctmdNewOrder procedure.
A form with command buttons that
perform overlapping functions. The
New Order button must do the same
tasks as Clear for Next Item.
Private Sub cmdNewOrder_Click()
‘Clear the current item and the current order
cmdClear_Click
‘Call the procedure for the click event of cmdClear
. . .
‘Continue with statements to clear subtotals
In the cmdNewOrder_Click() procedure, all the instructions in cmdClear_Click are executed. Then execution
returns to the next statement following the call.
Your Hands-On Programming Example
Create a project for R ‘n R – for Reading ‘n Refreshment that calculates the amount due for individual orders and
maintain accumulated totals for a summary. Have a check box for takeout items, which are taxable (12 percent); all
other orders are nontaxable. Include option buttons for the five coffee selections – Cappuccino, Espresso, Latte, Iced
Cappuccino, and Iced Latte. The prices for each will be assigned using these constants:
Cappuccino
2.00
Espresso
Latte
Iced (either)
2.25
1.75
2.50
Used a command button for Calculate Selection, which will calculate and display the amount due for each item.
A button for New Item will clear the selections and amount for the single item. Additional labels in a separate frame will
maintain the summary information for the current order to include subtotal, tax, and total.
Buttons at the bottom of the form will be used for New Order, Summary, and Exit. The new Order button will
clear the bill for the current customers and add to the totals for the summary. The button for Summary should display
the average sale amount per customer and the number of customers in a message box.
Download