decisions with if statements chapter 4. 2 structures sequence structure (so far) each statement...
TRANSCRIPT
Decisions with If Statements
Chapter 4
Chapter 4 2
Structures
Sequence Structure (so far) Each statement executed in sequence w/o
branching into other directions. Example:
Const dblRATE As Double = 0.15 Dim dblSubTotal As Double Dim dblDiscount As Double dblSubTotal = val(txtSubtotal.Text) dblDiscount = dblSubTotal * dblRATE lblDiscount.Text = FormatCurrency(dblDiscount)
Chapter 4 3
Structures, cont.
Decision Structure Algorithms often need to execute statements
only when a particular condition exists. Programmers write code that provides more
than one path of execution—based on particular circumstance.
Create a decision structure or tree to illustrate the flow.
Chapter 4 4
Logical Expressions
Alternative actions based on conditions of the situation.
Examples: Billing program causing overdue-payment
notice Payroll program to pay overtime Bonus based on annual performance
evaluation
Chapter 4 5
Condition, Action if True, Action if False
Condition Action if True Action if False
I am really, really hungry.
Eat at Tucano’s. Don’t eat anything.
It is 12:55 p.m. on Tuesday, February 10.
Go to BU 271 for your favorite VB class (of course).
Continue eating at Tucano’s.
Chapter 4 6
Flowchart
Condition to Test
Process ifCondition is True
Process ifCondition is False
True False
Chapter 4 7
Flowchart
Condition to Test
Process ifCondition is True
Process ifCondition is False
True False
Diamond:Yes/no question
Rectangle:Process that is conditionallyexecuted
Chapter 4 8
Example Flowchart
I am hungry.
Drive to Tucano’s Go to comp. lab.
True False
Eat!Do ISYS 1200Assignment.
Chapter 4 9
Pizza Flowchart
Create flowchart for #1 on p. 257.
Chapter 4 10
Executes one group of statements if the condition is true and another group of statements if the condition is false.
If condition Thenstatementblock1statementblock1
Elsestatementblock2statementblock2
End If Syntax Rules:
Start with If Include Then on same line as If End process with End If
If…Then…Else Statement
Only executed if condition is true
Only executed if condition is false
Chapter 4 11
Relational Operators Form Condition A testing expression that evaluates
as True or False. Relational operators determines
whether a specific relationship exists between two values. (See Tables 4.1 and 4.2).
Examples: Const intWEEK40 as Single =
40 Dim sngHours as Single sngHours > intWEEK40 sngHours <= intWEEK40 sngHours <> intWEEK40
Symbol Name
< Less than
<= Less than or equal to
> Greater than
>= Greater than or equal to
= Equal to
<> Not equal
Chapter 4 12
Relational Expression
Relational operators are binary. Require two operands dblLength > dblWidth intAge <= intMINOR
Relational expressions are evaluated as true or false only; they are not assignment statements. If x = y Then Determines if x and y are equal. If both operands are equal, then expression is
true.
Chapter 4 13
<=, >=, and <>
> or < must precede = No space between symbols Examples:
X >= Y X <= Y X <>Y
Chapter 4 14
Statement Block Processed if Condition is True Follows “Then” keyword. Completes series of statements until “Else” or “End If”
statement, whichever comes first. Const intMINRATE As Integer = 5
Dim intRating As IntegerintRating = val(txtValue.Text)If intRating > intMINRATE Then 'condition
dblBonus = dblSales * intHIGHRATE 'True processElse
dblBonus = dblSales * intLOWRATE
End If Processes True statement block code
and skips over the Else statement block.
Chapter 4 15
Statement Block Processed if Condition is False Follows the keyword “Else.” Completes series of statements until “End If” statement. Const intMINRATE As Integer = 5
Dim intRating As Integer intRating = val(txtValue.Text)If intRating > intMINRATE Then 'condition
dblBonus =dblSales * intHIGHRATE 'True process
ElsedblBonus = dblSales * intLOWRATE 'False process
End If Skips “True” statement block since false and processes
statement block after keyword “Else.”
Chapter 4 16
Standard Conventions
While many formats work, use the standard convention of indenting statement blocks to enhance readability (see p. 189).
If condition Thentrue process
Elsefalse process
End If
Chapter 4 17
Multiple Process Lines
If condition is true, continues processing all lines between “Then” and “Else.”
If condition is false, processes all lines between “Else” and “End If.”
If dblSales > 50000 ThenblnGetsBonus = TruedblCommissionRate = 0.12intDaysOff = intDaysOff + 1
End If
Chapter 4 18
Relational Operators and Math Operators Can combine within same expression. Math operators performed first. If intAge + intYears = 80 Then
lblMessage.Text = “You can retire.”End If
If intAge + intYears > 30+25 ThenlblMessage.Text = “You get a raise.”
End If
Chapter 4 19
Val () Function
If Val(txtInput.Text) > 100 ThenintBonus = 1000
End If Intrinsic Val function gets numeric value of
text box Text property. The returned value is compared to 100. If the returned value is > 100, the assignment
statement executes.
Chapter 4 20
Checkpoint
Do exercises on pp. 191-192
Chapter 4 21
Checkpoint (p. 195)
X = 0If x < 1 Then
y = 99Else
y = 0End If
X = 100If x <=1 Then
y = 99Else
y = 0End If
Expression is trueY = 99
Expression is falseY = 0
Chapter 4 22
Practice Exercise w/ Event Procedure
Get revenue and cost from a user. If the revenue is greater than the cost, calculate the profit and display it in a label with a string of text. Otherwise, calculate the loss and display the loss amount with a description in the label.
Chapter 4 23
Practice Solution
Dim dblRevenue as Currency ‘dim other vars also dblRevenue = val(txtRevenue.Text) dblCost = val(txtCost.Text) If dblRevenue > dblCost Then
dblProfit = dblRevenue – dblCostlblResult.Text = "The company had _
a profit of " & Profit & "."Else
dblLoss = dblCost – dblRevenuelblResult.Text = "The company had _
a loss of " & Loss & ".“End If
Chapter 4 24
Practice Examples
Tutorial 4-2 (pp. 193-195) Programming Challenge 1 (p. 258)
Chapter 4 25
Boolean Variable (p. 118 & pp. 190-191)
Stores True or False only.
Stores results of logical expression
Uses Boolean contents to complete decision process in If…Then…Else block
Programmers use Booleans to test conditions or set flags.
A flag is a Boolean variable that signals when some condition exists.
Chapter 4 26
Boolean Example
When flag is false, the condition does not exist. When flag is true, the condition exists.
Note: You do not need to use = True to compare the variable to true.
Chapter 4 27
Compound ConditionsUsing Logical Operators (pp. 206-211) Evaluates multiple conditions. Uses logical operators to connect 2 or more
relational expressions into one expression. And Or Xor Not
Chapter 4 28
And Operator
Connects 2 expressions. Requires that both expressions evaluate to
true. Identify job candidates with > 5 years AND
knows at least 3 programming languages If intYears > 5 And intLang >=3 Then If BOTH are true, follow THEN statement. If Years = 5 and Language = 3, follow ELSE
statement.
Chapter 4 29
And Truth TableJob Candidates
Experience and Language
Both conditions must be true to evaluate as True.
Test 1 (over 5 years experience)
True False
Test 2
Languages 3+
True True False
False False False
Chapter 4 30
Create And Example
Create the following: Experience (label caption) txtExperience (empty text box) Languages (label caption) txtLanguages (empty text box) Check Qualifications (button)
Chapter 4 31
And Logical Operator Example
Compare variable value to constant value using relational operator >. Use parentheses around each comparison (not required by assists with
readability). Type And logical operator to require that both relational expressions
(conditions) are met. Compare variable value to constant value using relational operator >=. Run with 5 & 3 (both conditions not met). Run with 6 & 3 (both conditions met).
Chapter 4 32
Boolean Example
Declare Boolean variable.
Sets Boolean flag to true ifboth conditions are met.
If trigger is true, do something.
Chapter 4 33
Or Operator
Combines 2 expressions. Requires that only one expression is true—
doesn’t matter which expression is true. Checks condition to left of Or operator.
If that condition is true, the whole expression is evaluated as true.
The program does not check the expression on the right side of the Or operator (to avoid wasting CPU time to check 2nd condition).
If condition on left side of Or operator is false, program must check 2nd condition.
Chapter 4 34
Or Truth Table
At least one of the expressions must be true; doesn’t matter which one.
Test 1
(over 5 years)
True False
Test 2
(3+ languages)
True True True
False True False
Chapter 4 35
Or Example
If Temp < 20 Or Temp > 100 ThenlblResult.Text = “Warning”
End If Doesn’t matter if temp is 19 or 101—either
one is true and will produce warning.
Chapter 4 36
Or Example Change And to Or
Run with 6 and 1 6 is > than 5 Program does not even check 2nd condition
Run with 4 and 3 4 is not > 5 (false condition) Program evaluates 2nd condition 3 >= 3 (true) Thus: entire expression is true
Chapter 4 37
Xor Operator
Exclusive Or Creates an expression that is true when one
(not both) of the subexpressions is true. If intYears > 5 Xor intNumJobs > 3 intYears = 6; intNumJobs = 3 True intYears = 5; intNumJobs = 4 True intYears = 6; intNumJobs = 4 False
Chapter 4 38
Xor Truth Table
ONLY one condition must be true; doesn’t matter which one; if both conditions are true, the entire expression is false
Test 1
(over 5 years)
True False
Test 2
(3+ languages)
True False True
False True False
Chapter 4 39
Not Truth Table
Opposite
Reverses the logical value of an expression: makes a true expression false and a false expression true.
Test 1 (only 1)
True False
False True
Chapter 4 40
Not Example
Reverses the truth If Not Age >= 21 Then
lblNote.Text = "You are underage _ and can’t buy alcoholic beverages. _Drink Wild Cherry Pepsi!"
ElselblNote.Text = "You are legal. Drink _whatever you want—in moderation."
End If
Chapter 4 41
Business Computer Proficiency
Students must earn 80% on each test. If Not dblScore >= dblPROFICIENT Then
lblOutput.Text = “Take the test again.”Else
lblOutput.Text = “Congratulations!”End If
If dblScore < dblPROFICIENT ThenlblOutput.Text = “Take the test again.”
ElselblOutput.Text = “Congratulations!”
End If Same results; note the difference in relational operators.
Chapter 4 42
Input Validation (p. 235)
Checking to verify that appropriate values have been entered in a text box. Data entered. Data is numeric. Specific value is entered. Check range of values. Positive value entered (instead of negative).
Necessary before performing calculations to avoid run-time errors.
Chapter 4 43
Validate for No Input (p. 213)
Make sure text box is not empty upon click command button.
Does not detect string of spaces because spaces are characters like “ABC.”
If txtYears.Text = "" Then'display error message'set focus'exit the event procedure
End If
Chapter 4 44
IsNumeric() Validation (p. 216-217)
Evaluates argument in parentheses. Returns True or False based on if argument is valid
number. Example:
IsNumeric(“12a”) returns false IsNumeric(txtAge.Text) returns true if numeric IsNumeric(txtAge.Text) returns false if not
numeric
Helps avoid Type Mismatch error at run time. Evaluates user input, can display MessageBox (error
message) if not valid number.
Chapter 4 45
IsNumeric() Example
If IsNumeric(txtQuantity.Text) ThenintQuantity = Val(txtQuantity.Text)dblAmountDue = intQuantity * dblPRICE
ElseMessageBox("Nonumeric data entered.", _
"Invalid Data“)'Select text in text box for user to retype.
End If Add input validation for numeric to existing
program example to test for numeric years & number of languages.
Chapter 4 46
Validate for Correct Range
If Val(txtHours.Text) < 50 And Val(txtHours.Text) > 10 Then'perform code
Else'display MessageBox error'select text box to re-enter dataExit Sub ‘exits rest of even procedure to avoid
‘performing calculationsEnd If
Chapter 4 47
Validating for Numeric and w/in a Certain Range Use Not IsNumeric as the first condition to
determine if the text box contents are not numeric values. Returns True if the text box does not contain numbers. Also used to return error message if text box I empty.
(Spaces count as characters though.) Create condition to test for range or to avoid negative
value as the second condition. Provide error message, set focus, and exit the event
procedure if data entry does not validate. Omit Else statement and continue statements after
End If to continue processing.
Chapter 4 48
Selecting Text Contents Upon Receiving Focus (p. 312) Select entire contents of text box upon
receiving focus. See Save As dialog box in PowerPoint.
Notice that entire contents of the File name text box are selected. White letters on a blue background
Chapter 4 49
Selecting Existing Text Box Contents
txtTextBoxName.SelectionStart = 0 Specifies text box name. SelectionStart property holds position of the
first selected character. In this case it starts with the first character (0 = first character).
txtTextBoxName.SelectionLength Holds the # of characters that are selected. If use txtName.SelectionLength = 5, then 5
characters are selected.
Chapter 4 50
Selecting Text Box Contents
txtName.Text.Length Gets the length of the text box content. Applies to other selection statements as well (see
string examples on p. 217). txtName.SelectionStart = 0
txtName.SelectionLength = txtName.Text.Length The above two statements identify & select the
entire text box contents (see p. 312). txtName.SelectAll
The above statement also selects the entire text box contents.
Use in a GotFocus event procedure.
Chapter 4 51
Nested If (p. 203)
If statement within another If statement. If condition in the main If expression is true,
then process an internal If statement. If condition in the main If expression is false,
then process a different internal If statement. Examine nested If statement in Tutorial 5
(pp. 203-205)
Chapter 4 52
Nested If
If condition ThenIf nestedcondition Then
perform actionsElse
perform other actionsEnd If
Elseperform action
End If
Chapter 4 53
Example
5% commission on sales under $10,000 10% commission on sales between
$10,000 and $20,000 15% commission on sales over $20,000 Create 3 controls
txtSales btnCalculate lblCommission
What do you need to declare? Write event procedure.
Chapter 4 54
Declarations & Variable Assignment
Before continuing to the next slide, think about how to structurethe nested If statement.
Use a flowchart if necessary.
Chapter 4 55
Nested If
Chapter 4 56
If…Then…ElseIf…Else (p. 196)
Another way to do nested If to create decision-making structures.
Sequence is critical because the order in which the rules are consulted.
Chapter 4 57
If…ElseIf…Else Example
Compare examples•2 lines shorter than nested Ifs (2 slides back)•Can only be ONE Else statement here (compared to 2 on nested If)•No ElseIf can follow an Else•Else must be last set of code; it catches any value that falls through the cracks.
•Edit program with this approach.•Review Tutorial 4-3 on pp. 196-202.
Chapter 4 58
More MessageBox Information
Multiple buttons, such as Yes and No
Determine action based on which button user clicks.
DialogResult.Abort DialogResult.OK
DialogResult.Retry DialogResult.Cancel
DialogResult.Ignore DialogResult.Yes
DialogResult.No
Chapter 4 59
Determine MessageBox Button Clicked Declare integer variable to store MessageBox
button.
Dim intResult as Integer intResult = MessageBox.Show(“Do you want to continue?”, _
“Please Confirm”, MessageBoxButtons.YesNo) If intResult = DialogResult.Yes Then
‘Perform an action hereElseIf intResult = DialogResult.No Then
‘Perform a different action hereEnd If