Download presentation
Presentation is loading. Please wait.
Published byAlvin Rich Modified over 9 years ago
1
Chapter 4: The Selection Structure Programming with Microsoft Visual Basic 2005, Third Edition
2
2 The If…Then…Else Statement Lesson A Objectives Write pseudocode for the selection structure Create a flowchart to help you plan an application’s code Write an If...Then...Else statement Write code that uses comparison operators and logical operators
3
3 Programming with Microsoft Visual Basic 2005, Third Edition The If…Then…Else Statement Lesson A Objectives (continued) Change the case of a string Determine whether a text box contains data Determine the success of the TryParse method
4
4 Programming with Microsoft Visual Basic 2005, Third Edition The Selection Structure Condition: expression evaluating to true or false Selection (decision) structure –Chooses one of two paths based on a condition Example –If employee works over 40 hours, add overtime pay Four selection structures in Visual Basic –If, If/Else, If/ElseIf/Else, and Case
5
5 Programming with Microsoft Visual Basic 2005, Third Edition Writing Pseudocode for If and If/Else Selection Structures If selection structure –Contains only one set of instructions –Instructions are processed if the condition is true If/Else selection –Contains two sets of instructions –True path: instruction set following true condition –False path: instruction set following false condition
6
6 Programming with Microsoft Visual Basic 2005, Third Edition Writing Pseudocode for If and If/Else Selection Structures Figure 4-4: Examples of the If and If/Else selection structures written in pseudocode
7
7 Programming with Microsoft Visual Basic 2005, Third Edition Flowcharting the If and If/Else Selection Structures Flowchart –Set of standardized symbols showing program flow Oval: the start/stop symbol Rectangle: the process symbol Parallelogram: the input/output symbol Diamond: selection/repetition symbol
8
8 Programming with Microsoft Visual Basic 2005, Third Edition Flowcharting the If and If/Else Selection Structures (continued) Figure 4-5: Examples of the If and If/Else selection structures drawn in flowchart form
9
9 Programming with Microsoft Visual Basic 2005, Third Edition Coding the If and If/Else Selection Structures Syntax –If condition Then statement block for true path [Else statement block for false path] End If condition must be a Boolean expression The Else clause is optional
10
10 Programming with Microsoft Visual Basic 2005, Third Edition Comparison Operators Comparison (relational) operators: –Test two items for equality or types of non-equality Rules for comparison operators –Cause an expression to evaluate to true or false –Have lower precedence than arithmetic operators –Are evaluated from left to right Example: 5 -2 > 1 + 2 3 > 3 False
11
11 Programming with Microsoft Visual Basic 2005, Third Edition Comparison Operators (continued) Figure 4-7: Listing and examples of commonly used comparison operators (continued)
12
12 Programming with Microsoft Visual Basic 2005, Third Edition Comparison Operators (continued) Figure 4-7: Listing and examples of commonly used comparison operators
13
13 Programming with Microsoft Visual Basic 2005, Third Edition xDisplayButton Click event procedure – pseudocode –Store text box values in the num1 and num2 variables –If the value of num1 is greater than the value of num2 Swap numbers so num1 contains the smaller number –End if –Display message stating lowest and highest numbers Block scope: restricts variable to a statement block Swap variable in if clause will have block scope Using Comparison Operators– Swapping Numeric Values
14
14 Programming with Microsoft Visual Basic 2005, Third Edition Using Comparison Operator– Swapping Numeric Values (continued) Figure 4-11: The If selection structure shown in the xDisplayButton’s Click event procedure
15
15 Programming with Microsoft Visual Basic 2005, Third Edition Using Comparison Operators— Displaying the Sum or Difference xCalcButton Click event procedure – pseudocode –Store values in operation, number1, and number2 –If the operation variable contains “1” Calculate the sum of number1 and number2 Display the “Sum:” message along with the sum –Else Subtract number2 from number1 Display “Difference:” message along with difference –End if
16
16 Programming with Microsoft Visual Basic 2005, Third Edition Using Comparison Operators— Displaying the Sum or Difference (continued) Figure 4-16: The If/Else selection structure shown in the xCalcButton’s Click event procedure
17
17 Programming with Microsoft Visual Basic 2005, Third Edition Logical Operators Logical (Boolean) operators –Operators that create compound conditions –Types: And, Or, Not, AndAlso, OrElse, Xor Example: If hours > 0 And hours <= 40 Then Truth tables: show how operators are evaluated Short circuit evaluation: bypasses a condition –Operators using technique: AndAlso, OrElse Example: If state = "TN" AndAlso st > 50000D Then –If st is not TN, no need to evaluate sales > 50000D
18
18 Programming with Microsoft Visual Basic 2005, Third Edition Logical Operators (continued) Figure 4-18: Listing and examples of logical operators (partial)
19
Logical Operators (continued) Truth table for Not operator If condition isValue of Result is TrueFalse True Result = Not Condition
20
Logical Operators (continued) Truth table for And operator If condition1 isAnd condition2 isValue of Result is True False TrueFalse Result = condition1 And Condition2
21
Logical Operators (continued) Truth table for AndAlso operator If condition1 isAnd condition2 isValue of Result is True False (not evaluated)False Result = condition1 AndAlso Condition2
22
Logical Operators (continued) Truth table for Or operator If condition1 isAnd condition2 isValue of Result is True FalseTrue FalseTrue False Result = condition1 Or Condition2
23
Logical Operators (continued) Truth table for OrElse operator If condition1 isAnd condition2 isValue of Result is True(not evaluated)True FalseTrue False Result = condition1 OrElse Condition2
24
Logical Operators (continued) Truth table for Xor operator If condition1 isAnd condition2 isValue of Result is True False TrueFalseTrue FalseTrue False Result = condition1 Xor Condition2
25
25 Programming with Microsoft Visual Basic 2005, Third Edition Using the Truth Tables Scenario: calculate a bonus for a salesperson –Bonus condition: “A” rating and sales > $10,000 –Appropriate operators: And, AndAlso (more efficient) –Both conditions must be true to receive bonus –Sample code: rating = "A" AndAlso sales > 10000 Precedence of logical operators –Lower than that of arithmetic or comparison operators
26
26 Programming with Microsoft Visual Basic 2005, Third Edition Using Truth Tables (continued) Figure 4-20: Order of precedence for arithmetic, comparison, and logical operators
27
27 Programming with Microsoft Visual Basic 2005, Third Edition Using Logical Operators: Calculating Gross Pay Data validation: verifying input data is within range Scenario: calculate and display employee gross pay Requirements for application implementing scenario –Verify hours are within range (>= 0.0 and <= 40.0) –If data is valid, calculate and display gross pay –If data is not valid, display error message Compound condition can use AndAlso or OrElse
28
28 Programming with Microsoft Visual Basic 2005, Third Edition Using Logical Operators: Calculating Gross Pay (continued) Figure 4-22: AndAlso and OrElse logical operators in the If...Then...Else statement (continued)
29
29 Programming with Microsoft Visual Basic 2005, Third Edition Using Logical Operators: Calculating Gross Pay (continued) Figure 4-22: AndAlso and OrElse logical operators in the If...Then...Else statement
30
30 Programming with Microsoft Visual Basic 2005, Third Edition Comparing Strings Containing Letters Scenario –Display “Pass” if ‘P’ is entered in xLetterTextBox –Display “Fail” if ‘F’ is entered in xLetterTextBox One of the possible implementations –Dim letter As String letter = Me.xLetterTextBox.Text If letter = "P" OrElse letter = "p“ Then Me.xResultLabel.Text = “Pass“ Else Me.xResultLabel.Text = "Fail“ End if
31
31 Programming with Microsoft Visual Basic 2005, Third Edition Converting a String to Uppercase or Lowercase String comparisons are case sensitive CharacterCasing property –Three case values: Normal (default), Upper, Lower ToUpper method: converts string to upper case ToLower method: converts string to lower case Example: If letter.ToUpper = "P" Then
32
32 Programming with Microsoft Visual Basic 2005, Third Edition Using the ToUpper and ToLower Methods: Displaying a Message Procedure requirements –Display message “We have a store in this state” –Valid states: IL, IN, KY –Account for case variations in state text entered Choices for controlling case: ToLower or ToUpper One way to enforce case for input –Dim state As String state = Me.xStateTextBox.Text.ToUpper –Use If/Else to test state value and display message
33
33 Programming with Microsoft Visual Basic 2005, Third Edition Comparing Boolean Values Boolean variable: contains either true or false Naming convention: “is” denotes Boolean type –Example: isInsured Determining whether a text box contains data –Compare Text property to String.empty value or “” –Alternative: use String.IsNullorEmpty method Determining whether a string can be converted to a number –Use Boolean value returned by TryParse method
34
34 Programming with Microsoft Visual Basic 2005, Third Edition Comparing Boolean Values (continued) Figure 4-29: Syntax and examples of the String.IsNullOrEmpty method
35
35 Programming with Microsoft Visual Basic 2005, Third Edition Comparing Boolean Values (continued) Figure 4-31: Syntax and an example of using the Boolean value returned by the TryParse method
36
36 Programming with Microsoft Visual Basic 2005, Third Edition Summary – Lesson A A Boolean condition evaluates to true or false Selection structures choose an instruction path based on a condition If...Then...Else statement: selection structure with a true path and a false path Operator precedence: arithmetic, comparison, logical ToUpper and ToLower modify case of input text
37
37 Programming with Microsoft Visual Basic 2005, Third Edition The Monthly Payment Calculator Application Lesson B Objectives Group objects using a GroupBox control Calculate a periodic payment using the Financial.Pmt method Create a message box using the MessageBox.Show method Determine the value returned by a message box
38
38 Programming with Microsoft Visual Basic 2005, Third Edition Completing the User Interface Need: calculate monthly payment on a car loan To make this calculation, the application needs: –The loan amount (principal) –The annual percentage rate (APR) of interest –The life of the loan (term) in years
39
39 Programming with Microsoft Visual Basic 2005, Third Edition Completing the User Interface (continued) Figure 4-34: Sketch of the Monthly Payment Calculator user interface
40
40 Programming with Microsoft Visual Basic 2005, Third Edition Adding a Group Box to the Form Group box: container for other controls GroupBox tool –Located in the Toolbox window –Used to add a group box control to the interface Purpose of a group box control –Visually separate related controls from other controls Lock controls and set TabIndex after placement
41
41 Programming with Microsoft Visual Basic 2005, Third Edition Coding the Monthly Payment Calculator Application Procedures required according to TOE chart –Click event code for the two buttons –TextChanged, KeyPress, Enter code for text boxes Procedures that are already coded –xExitButton’s Click event and TextChanged events Procedure to code in Lesson B –xCalcButton’s Click event procedure
42
42 Programming with Microsoft Visual Basic 2005, Third Edition Coding the xCalcButton’s Click Event Procedure Tasks for xCalcPayButton’s Click event procedure –Calculating the monthly payment amount –Displaying the result in the xPaymentLabel control Two selection structures needed: If and If/Else Determining named constants and variables –Constants: items that do not change with each call –Variables: items will likely change with each call
43
43 Programming with Microsoft Visual Basic 2005, Third Edition Coding the xCalcPayButton Click Event Procedure (continued) Figure 4-39: Pseudocode for the xCalcButton’s Click event procedure
44
44 Programming with Microsoft Visual Basic 2005, Third Edition Using the Financial.Pmt Method Calculates periodic payment on loan or investment Syntax: Financial.Pmt(Rate, NPer, PV[, FV, Due]) –Rate: interest rate per period –NPer: total number of payment periods (the term) –PV: present value of the loan or investment –FV: future value of the loan or investment –Due: due date of payments
45
45 Programming with Microsoft Visual Basic 2005, Third Edition The MessageBox.Show Method Displays message box with text, button(s), icon Syntax: MessageBox.Show(text, caption, buttons, icon[, defaultButton]) –text: text to display in the message box –caption: text to display in title bar of message box –buttons: buttons to display in the message box –icon: icon to display in the message box –defaultButton: automatically selected if Enter pressed
46
46 Programming with Microsoft Visual Basic 2005, Third Edition The MessageBox.Show Method (continued) Figure 4-48: Completed xCalcButton’s Click event procedure
47
47 Programming with Microsoft Visual Basic 2005, Third Edition The MessageBox.Show Method (continued) Figure 4-50: Message box created by the MessageBox.Show method
48
48 Programming with Microsoft Visual Basic 2005, Third Edition Summary – Lesson B Group box control treats components as one unit Add a group box using the GroupBox tool Financial.Pmt method calculates loan or investment payments MessageBox.Show method displays a message box with text, one or more buttons, and an icon
49
49 Programming with Microsoft Visual Basic 2005, Third Edition Completing the Monthly Payment Calculator Application Lesson C Objectives Specify the keys that a text box will accept Select the existing text in a text box
50
50 Programming with Microsoft Visual Basic 2005, Third Edition Coding the KeyPress Event Procedures KeyPress event –Occurs when key pressed while a control has focus –Character corresponding to key is stored –Stored value sent to KeyPress event’s e parameter One popular use of the KeyPress event –Prevents users from entering inappropriate characters –Selection structure used to test entered character
51
51 Programming with Microsoft Visual Basic 2005, Third Edition Coding the KeyPress Event Procedures (continued) Figure 4-54: Completed CancelKeys procedure
52
52 Programming with Microsoft Visual Basic 2005, Third Edition Coding the Enter Event Procedure Enter event –Occurs when the text box receives the focus –Responsible for selecting contents of text box –User can replace existing text by pressing a key SelectAll method syntax: Me.textbox.SelectAll() –Selects all text contained on a text box Using the SelectAll method –Add to each text box’s Enter event procedure
53
53 Programming with Microsoft Visual Basic 2005, Third Edition Coding the Enter Event Procedure (continued) Figure 4-57: Existing text selected in the xPrincipalTextBox
54
54 Programming with Microsoft Visual Basic 2005, Third Edition Summary – Lesson C KeyPress event procedure: responds to the user pressing a key One use of a KeyPress event: cancel a key entered by the user Enter event: occurs when text box receives focus SelectAll method: used to select all contents of a text box
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.