Programming with Microsoft Visual Basic 2008 Fourth Edition
Programming with Microsoft Visual Basic 2008 Fourth Edition Chapter Four The Selection Structure
Previewing the Monthly Payment Calculator Application • The Monthly Payment Calculator application uses the selection structure Programming with Microsoft Visual Basic 2008, Fourth Edition 2
Previewing the Monthly Payment Calculator Application (continued) Figure 4 -2: Monthly payment amount shown in the interface Programming with Microsoft Visual Basic 2008, Fourth Edition 3
Lesson A Objectives After studying Lesson A, you should be able to: • 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 • Change the case of a string • Determine the success of the Try. Parse method Programming with Microsoft Visual Basic 2008, Fourth Edition 4
The Selection Structure • Selection structure: – Chooses one of two paths based on condition – Also called a decision structure • Example: – If employee works over 40 hours, add overtime pay • Condition: Expression evaluating to true or false • Four selection structures in Visual Basic: – If, If/Else, and Case Programming with Microsoft Visual Basic 2008, Fourth Edition 5
The Selection Structure (continued) Figure 4 -3: Selection structures you might use today Programming with Microsoft Visual Basic 2008, Fourth Edition 6
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 structure: – Contains two sets of instructions – True path: Instruction set following true condition – False path: Instruction set following false condition Programming with Microsoft Visual Basic 2008, Fourth Edition 7
Writing Pseudocode for If and If/Else Selection Structures (continued) Figure 4 -4: Examples of the If and If/Else selection structures written in pseudocode Programming with Microsoft Visual Basic 2008, Fourth Edition 8
Flowcharting the If and If/Else Selection Structures • Flowchart: – Uses standardized symbols showing steps to be taken to accomplish a task • • Oval: Start/stop symbol Rectangle: Process symbol Parallelogram: Input/output symbol Diamond: Decision symbol – Used in both selection and repetition structures Programming with Microsoft Visual Basic 2008, Fourth Edition 9
Coding the If and If/Else Selection Structures • If…Then…Else statement: Used to code If and If/Else selections structures • Syntax: If condition Then statement block for true path [Else statement block for false path] End If – condition must be a Boolean expression that evaluates to True or False – Else clause is optional Programming with Microsoft Visual Basic 2008, Fourth Edition 10
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 Programming with Microsoft Visual Basic 2008, Fourth Edition 11
Comparison Operators • Comparison (relational) operators: – Used to test two items for equality or types of nonequality – Always result in a True or False value • Rules for comparison operators – They do not have an order of precedence – They are evaluated from left to right – They are evaluated after any arithmetic operators in the expression Programming with Microsoft Visual Basic 2008, Fourth Edition 12
Comparison Operators (continued) Figure 4 -8: Evaluation steps for an expression containing arithmetic and comparison operators Programming with Microsoft Visual Basic 2008, Fourth Edition 13
Using Comparison Operators— Swapping Numeric Values • Sample application displays the lowest and highest of two numbers entered by the user Programming with Microsoft Visual Basic 2008, Fourth Edition 14
Using Comparison Operators— Swapping Numeric Values (continued) Figure 4 -9: Sample run of the Lowest and Highest application Programming with Microsoft Visual Basic 2008, Fourth Edition 15
Using Comparison Operators— Swapping Numeric Values (continued) Figure 4 -10: Display button’s pseudocode showing the If selection structure Programming with Microsoft Visual Basic 2008, Fourth Edition 16
Using Comparison Operators— Swapping Numeric Values (continued) Figure 4 -11: Display button’s flowchart showing the If selection structure Programming with Microsoft Visual Basic 2008, Fourth Edition 17
Using Comparison Operators— Swapping Numeric Values (continued) Figure 4 -12: Display button’s Click event procedure showing the If selection structure Programming with Microsoft Visual Basic 2008, Fourth Edition 18
Using Comparison Operators— Swapping Numeric Values (continued) • Values input by the user are stored in variables with procedure scope • A temporary variable is used when values must be swapped – Declared within statement block • Block scope: Restricts use of variable to statement block in which it is declared Programming with Microsoft Visual Basic 2008, Fourth Edition 19
Using Comparison Operators— Swapping Numeric Values (continued) Figure 4 -13: Illustration of the swapping concept Programming with Microsoft Visual Basic 2008, Fourth Edition 20
Using Comparison Operators— Displaying the Sum or Difference • Sample application that displays the sum or difference of two numbers entered by the user Programming with Microsoft Visual Basic 2008, Fourth Edition 21
Using Comparison Operators— Displaying the Sum or Difference (continued) Figure 4 -14: Sample run of the Addition and Subtraction application Programming with Microsoft Visual Basic 2008, Fourth Edition 22
Using Comparison Operators— Displaying the Sum or Difference (continued) Figure 4 -15: Calculate button’s pseudocode showing the If/Else selection structure Programming with Microsoft Visual Basic 2008, Fourth Edition 23
Using Comparison Operators— Displaying the Sum or Difference (continued) Figure 4 -16: Calculate button’s flowchart showing the If/Else selection structure Programming with Microsoft Visual Basic 2008, Fourth Edition 24
Using Comparison Operators— Displaying the Sum or Difference (continued) Figure 4 -17: Calculate button’s Click event procedure showing the If/Else selection structure Programming with Microsoft Visual Basic 2008, Fourth Edition 25
Logical Operators • Logical operators: – Used to create compound conditions – Also called Boolean operators • Six logical operators in Visual Basic: – – – And Or Not And. Also Or. Else Xor Programming with Microsoft Visual Basic 2008, Fourth Edition 26
Logical Operators (continued) Figure 4 -18: Listing and examples of logical operators Programming with Microsoft Visual Basic 2008, Fourth Edition 27
Logical Operators (continued) • Truth tables: Show logical operators are evaluated • Short circuit evaluation: Bypasses evaluation of condition when outcome can be determined without it – Operators using technique: And. Also, Or. Else • Example: – If state = "TN" And. Also sales > 50000 D Then… – If state is not TN, no need to evaluate sales > 50000 D Programming with Microsoft Visual Basic 2008, Fourth Edition 28
Logical Operators (continued) Figure 4 -19: Truth tables for the logical operators Programming with Microsoft Visual Basic 2008, Fourth Edition 29
Logical Operators (continued) Figure 4 -19: Truth tables for the logical operators (continued) Programming with Microsoft Visual Basic 2008, Fourth Edition 30
Logical Operators (continued) Figure 4 -19: Truth tables for the logical operators (continued) Programming with Microsoft Visual Basic 2008, Fourth Edition 31
Using the Truth Tables • Scenario: Calculate a bonus for a salesperson – Bonus condition: “A” rating and sales > $10, 000 – Appropriate operators: And, And. Also (more efficient) – Both conditions must be true to receive bonus – Sample code: rating = "A" And. Also sales > 10000 • Precedence of logical operators: – Evaluated after any arithmetic or comparison operators in the expression Programming with Microsoft Visual Basic 2008, Fourth Edition 32
Using Logical Operators: Calculating Gross Pay • Data validation: Verifying that input data is within expected range • Scenario: Calculate and display employee gross pay • Requirements for application: – 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 • Can accomplish this using And. Also or Or. Else Programming with Microsoft Visual Basic 2008, Fourth Edition 33
Comparing Strings Containing Letters • Scenario: – Display “Pass” if ‘P’ is entered in txt. Letter control – Display “Fail” if ‘F’ is entered in txt. Letter control • Can use the Or. Else or the And. Also operator • Note that ‘P’ is not the same as ‘p’ – They have different Unicode values Programming with Microsoft Visual Basic 2008, Fourth Edition 34
Comparing Strings Containing Letters (continued) Figure 4 -23: Visual Basic code showing string comparisons in the If. . . Then. . . Else statement’s condition Programming with Microsoft Visual Basic 2008, Fourth Edition 35
Comparing Strings Containing Letters (continued) Figure 4 -23: Visual Basic code showing string comparisons in the If. . . Then. . . Else statement’s condition (continued) Programming with Microsoft Visual Basic 2008, Fourth Edition 36
Converting a String to Uppercase or Lowercase • String comparisons are case sensitive • Character. Casing property: – Three case values: Normal (default), Upper, Lower • To. Upper method: Converts string to upper case • To. Lower method: Converts string to lower case • Example: If str. Letter. To. Upper = “p" Then – Note that str. Letter’s value is not permanently converted Programming with Microsoft Visual Basic 2008, Fourth Edition 37
Converting a String to Uppercase or Lowercase (continued) Figure 4 -24: Syntax and examples of the To. Upper and To. Lower methods Programming with Microsoft Visual Basic 2008, Fourth Edition 38
Converting a String to Uppercase or Lowercase (continued) Figure 4 -24: Syntax and examples of the To. Upper and To. Lower methods (continued) Programming with Microsoft Visual Basic 2008, Fourth Edition 39
Using the To. Upper and To. Lower Methods: Displaying a Message • Procedure requirements: – Display message “We have a store in this state” – Valid states: IL, IN, KY – Must handle case variations in the user’s input • Can use To. Lower or To. Upper • Can assign a String variable to the input textbox’s value converted to upper case Dim str. State As String str. State = txt. State. Text. To. Upper • Use If/Else to test value and display message Programming with Microsoft Visual Basic 2008, Fourth Edition 40
Comparing Boolean Values • Boolean variable: Contains either True or False • Naming convention: “Is” denotes Boolean type – Example: bln. Is. Insured • When testing for a True value, it is not necessary to include the “= True” – Examples: If bln. Is. Insured = True Then or If bln. Is. Insured Then • Use Not logical operator to test for False value Programming with Microsoft Visual Basic 2008, Fourth Edition 41
Comparing Boolean Values (continued) Figure 4 -27: Examples of comparing Boolean values in an If…Then…Else statement’s condition Programming with Microsoft Visual Basic 2008, Fourth Edition 42
Comparing Boolean Values: Determining Whether a String Can Be Converted to a Number • Determining whether a string can be converted to a number: – Try. Parse method returns a numeric value after converting the string, or 0 if it cannot be converted – Try. Parse also returns a Boolean value indicating success or failure of the conversion attempt • Use Boolean value returned by Try. Parse method in an If…Then…Else statement Programming with Microsoft Visual Basic 2008, Fourth Edition 43
Comparing Boolean Values: Determining Whether a String Can be Converted to a Number (continued) Figure 4 -28: Syntax and example of using the Boolean value returned by the Try. Parse method Programming with Microsoft Visual Basic 2008, Fourth Edition 44
Lesson A Summary • Arithmetic operators are evaluated first, then comparison operators, and finally logical operators • If. . . Then. . . Else statement: Selection structure with a true path and a false path • Use comparison operators to compare two values • Use a temporary variable to swap values contained in two variables • Use logical operators to create a compound condition Programming with Microsoft Visual Basic 2008, Fourth Edition 45
Lesson A Summary (continued) • Use text box’s Character. Casing property to change text to upper or lower case • Use To. Upper and To. Lower to temporarily modify the case of input text • Use Boolean return value of Try. Parse method to determine whether string was successfully converted to numeric value Programming with Microsoft Visual Basic 2008, Fourth Edition 46
Lesson B Objectives After studying Lesson B, you should be able to: • Group objects using a Group. Box control • Calculate a periodic payment using the Financial. Pmt method • Create a message box using the Message. Box. Show method • Determine the value returned by a message box Programming with Microsoft Visual Basic 2008, Fourth Edition 47
Creating the Monthly Payment Calculator Application • Program requirement: Calculate monthly payment on car loan • To do so, application needs: – The loan amount (principal) – The annual percentage rate (APR) of interest – The life of the loan (term) in years Programming with Microsoft Visual Basic 2008, Fourth Edition 48
Adding a Group Box to the Form • Group box: Container control for other controls • Group. Box tool: – Used to add group box control to interface • Group box control provides: – Visual separation of related controls – Ability to manage the grouped controls by manipulating the group box control • Lock controls to ensure that they are not moved • Be sure to set Tab. Index after placement of controls Programming with Microsoft Visual Basic 2008, Fourth Edition 49
Coding the Monthly Payment Calculator Application • Procedures required according to TOE chart: – Click event procedure code for the two buttons – Code for Text. Changed, Key. Press, and Enter events for text boxes • Procedures that are already coded: – btn. Exit Click event and Text. Changed events for the text boxes • Procedure to code in Lesson B: – btn. Calc button’s Click event procedure Programming with Microsoft Visual Basic 2008, Fourth Edition 50
Coding the Monthly Payment Calculator Application (continued) Figure 4 -33: TOE chart for the Monthly Payment Calculator application Programming with Microsoft Visual Basic 2008, Fourth Edition 51
Coding the btn. Calc Control’s Click Event Procedure • Tasks for btn. Calc button’s Click event procedure: – Calculate monthly payment amount – Display result in lbl. Payment control • Two selection structures needed – If and If/Else • Determine interest rate and term • Determine need for named constants and variables within procedure – Constants: Items that do not change with each call – Variables: Items will likely change with each call Programming with Microsoft Visual Basic 2008, Fourth Edition 52
Coding the btn. Calc Control’s Click Event Procedure (continued) Figure 4 -34: Pseudocode for the btn. Calc control’s Click event procedure Programming with Microsoft Visual Basic 2008, Fourth Edition 53
Coding the btn. Calc Control’s Click Event Procedure (continued) Figure 4 -35: Partially completed Click event procedure Programming with Microsoft Visual Basic 2008, Fourth Edition 54
Using the Financial. Pmt Method • Calculates periodic payment on loan or investment • Must ensure that interest rate and number of periods are expressed in same units (months or years) – Convert an annual interest rate to monthly rate by dividing by 12 – Convert an annual term to a monthly term by multiplying by 12 Programming with Microsoft Visual Basic 2008, Fourth Edition 55
Using the Financial. Pmt Method (continued) Figure 4 -36: Basic syntax and examples of the Financial. Pmt method Programming with Microsoft Visual Basic 2008, Fourth Edition 56
Using the Financial. Pmt Method (continued) Figure 4 -37: Selection structure’s true path coded in the procedure Programming with Microsoft Visual Basic 2008, Fourth Edition 57
The Message. Box. Show Method • Message. Box. show method: Displays message box with text message, caption, button(s), and icon • Use sentence capitalization for text message • Use book title capitalization for caption • Icons: – Exclamation or Question: Indicates user must make a decision before continuing – Information: Indicates informational message – Stop: Indicates serious problem Programming with Microsoft Visual Basic 2008, Fourth Edition 58
The Message. Box. Show Method (continued) Figure 4 -41: Values returned by the Message. Box. Show method Programming with Microsoft Visual Basic 2008, Fourth Edition 59
The Message. Box. Show Method (continued) Figure 4 -41: Values returned by the Message. Box. Show method (continued) Programming with Microsoft Visual Basic 2008, Fourth Edition 60
Lesson B Summary • Group box is container control that treats its contents as one unit • Use Financial. Pmt method to calculate loan or investment payments • Message. Box. Show method displays message box with text, one or more buttons, and icon Programming with Microsoft Visual Basic 2008, Fourth Edition 61
Lesson C Objectives After studying Lesson C, you should be able to: • Prevent the entry of unwanted characters in a text box • Select the existing text in a text box Programming with Microsoft Visual Basic 2008, Fourth Edition 62
Coding the Key. Press Event Procedures • Key. Press event: – Occurs when key is pressed while control has focus – Character corresponding to pressed key is sent to Key. Press event’s e parameter • Key. Press event can be used to prevent users from entering inappropriate characters – Use e parameter’s Key. Char property to determine pressed key – Use Handled property to cancel key if needed Programming with Microsoft Visual Basic 2008, Fourth Edition 63
Coding the Key. Press Event Procedures (continued) Figure 4 -47: Code template for the txt. Principal’s Key. Press event procedure Programming with Microsoft Visual Basic 2008, Fourth Edition 64
Coding the Key. Press Event Procedures (continued) Figure 4 -48: Examples of using the Key. Char and Handled properties in the Key. Press event procedure Programming with Microsoft Visual Basic 2008, Fourth Edition 65
Coding the Key. Press Event Procedures (continued) Figure 4 -49: Completed Cancel. Keys procedure Programming with Microsoft Visual Basic 2008, Fourth Edition 66
Coding the Enter Event Procedure • Enter event: – Occurs when text box receives focus – If text is selected, user can replace existing text by pressing key • Can use Enter event to select all of text • Select. All method: Selects all text contained in text box – Add to each text box’s Enter event procedure Programming with Microsoft Visual Basic 2008, Fourth Edition 67
Coding the Enter Event Procedure (continued) Figure 4 -50: Syntax and an example of the Select. All method Programming with Microsoft Visual Basic 2008, Fourth Edition 68
Lesson C Summary • Key. Press event occurs when user presses key • Use Key. Press event to cancel unwanted key entered by user • Enter event occurs when text box receives focus • Use Enter event to process code when control receives focus • Use Select. All method to select all contents of text box Programming with Microsoft Visual Basic 2008, Fourth Edition 69
- Slides: 69