Programming with Microsoft Visual Basic 2010 5 th

Programming with Microsoft Visual Basic 2010 5 th Edition Chapter Four The Selection Structure

Previewing the Monthly Payment Calculator Application The Monthly Payment Calculator application uses the selection structure 2 Programming with Microsoft Visual Basic 2010, 5 th Edition

Figure 4 -1 Message box Figure 4 -2 Monthly payment amount shown in the interface 3 Programming with Microsoft Visual Basic 2010, 5 th Edition

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 Include comparison operators and logical operators in a selection structure’s condition Change the case of a string Determine the success of the Try. Parse method 4 Programming with Microsoft Visual Basic 2010, 5 th Edition

Making Decisions in a Program Three basic control structures Sequence Selection Repetition All procedures in an application are written using one of more of these structures Procedures in previous chapters used sequence structure only 5 Programming with Microsoft Visual Basic 2010, 5 th Edition

Making Decisions in a Program (cont’d. ) 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 Decision expression evaluating to true or false 6 Programming with Microsoft Visual Basic 2010, 5 th Edition

Making Decisions in a Program (cont’d. ) Single-alternative selection structure Tasks performed only when condition is true Dual-alternative selection structure One set of tasks performed if condition is true Called true path Different set of tasks performed if condition is false Called false path If and end if Denotes selection structure’s beginning and end Else denotes beginning of false path 7 Programming with Microsoft Visual Basic 2010, 5 th Edition

Making Decisions in a Program (cont’d. ) Figure 4 -3 Selection structures you might use today 8 Programming with Microsoft Visual Basic 2010, 5 th Edition

Making Decisions in a Program (cont’d. ) Example: Kanton Boutique Figure 4 -4 Problem specification for Kanton Boutique 9 Programming with Microsoft Visual Basic 2010, 5 th Edition

Figure 4 -5 Interface for the Kanton Boutique application Figure 4 -6 Pseudocode containing only the sequence structure 10 Programming with Microsoft Visual Basic 2010, 5 th Edition

Figure 4 -7 Modified problem specification and pseudocode containing a single-alternative selection structure 11 Programming with Microsoft Visual Basic 2010, 5 th Edition

Making Decisions in a Program (cont’d. ) Decision symbol Diamond shape in a flowchart Represents the selection structure’s condition Other symbols Oval: Start/stop symbol Rectangle: Process symbol Parallelogram: Input/output symbol 12 Programming with Microsoft Visual Basic 2010, 5 th Edition

Figure 4 -8 Single-alternative selection structure shown in a flowchart 13 Programming with Microsoft Visual Basic 2010, 5 th Edition

Figure 4 -9 Modified problem specification and pseudocode containing a dual-alternative selection structure 14 Programming with Microsoft Visual Basic 2010, 5 th Edition

Figure 4 -10 Dual-alternative selection structure shown in a flowchart 15 Programming with Microsoft Visual Basic 2010, 5 th Edition

Coding Single-Alternative and Dual. Alternative Selection Structures If…Then…Else statement Used to code single and dual-alternative selection structures Statement block Set of statements in each path Syntax and examples shown in Figure 4 -11 on next slide 16 Programming with Microsoft Visual Basic 2010, 5 th Edition

Figure 4 -11 Syntax and examples of the If…Then…Else statement (continues) 17 Programming with Microsoft Visual Basic 2010, 5 th Edition

Figure 4 -11 Syntax and examples of the If…Then…Else statement (cont’d. ) 18 Programming with Microsoft Visual Basic 2010, 5 th Edition

Comparison Operators Comparison operators Used to compare two values 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 19 Programming with Microsoft Visual Basic 2010, 5 th Edition

Figure 4 -12 Listing and examples of commonly used comparison operators 20 Programming with Microsoft Visual Basic 2010, 5 th Edition

Comparison Operators (cont’d. ) Using comparison operators: Swapping numeric values Sample application displays the lowest and highest of two numbers entered by the user Figure 4 -14 Sample run of the Lowest and Highest application 21 Programming with Microsoft Visual Basic 2010, 5 th Edition

Comparison Operators (cont’d. ) Figure 4 -15 Pseudocode containing a single-alternative selection structure 22 Programming with Microsoft Visual Basic 2010, 5 th Edition

Figure 4 -16 Flowchart containing a single-alternative selection structure 23 Programming with Microsoft Visual Basic 2010, 5 th Edition

Figure 4 -17 Display button’s Click event procedure 24 Programming with Microsoft Visual Basic 2010, 5 th Edition

Comparison Operators (cont’d. ) 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-level variable Block scope Restricts use of variable to statement block in which it is declared 25 Programming with Microsoft Visual Basic 2010, 5 th Edition

Comparison Operators (cont’d. ) Figure 4 -18 Illustration of the swapping concept 26 Programming with Microsoft Visual Basic 2010, 5 th Edition

Comparison Operators (cont’d. ) Using comparison operators: Displaying the sum or difference Sample application displays the sum or difference of two numbers entered by the user Figure 4 -19 Sample run of the Addition and Subtraction application 27 Programming with Microsoft Visual Basic 2010, 5 th Edition

Comparison Operators (cont’d. ) Figure 4 -20 Pseudocode containing a dual-alternative selection structure 28 Programming with Microsoft Visual Basic 2010, 5 th Edition

Figure 4 -21 Pseudocode containing a dual-alternative selection structure 29 Programming with Microsoft Visual Basic 2010, 5 th Edition

Figure 4 -22 Calculate button’s Click event procedure 30 Programming with Microsoft Visual Basic 2010, 5 th Edition

Logical Operators Logical operators Used to create compound conditions Expressions evaluate to a Boolean value True or False Six logical operators in Visual Basic Not, And. Also, Or. Else, Xor 31 Programming with Microsoft Visual Basic 2010, 5 th Edition

Figure 4 -23 Listing and examples of logical operators (continues) 32 Programming with Microsoft Visual Basic 2010, 5 th Edition

Figure 4 -23 Listing and examples of logical operators (cont’d. ) 33 Programming with Microsoft Visual Basic 2010, 5 th Edition

Logical Operators (cont’d. ) 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 > $5000 Then… If state is not TN, no need to evaluate sales > $5000 34 Programming with Microsoft Visual Basic 2010, 5 th Edition

Figure 4 -24 Truth tables for the logical operators 35 Programming with Microsoft Visual Basic 2010, 5 th Edition

Logical Operators (cont’d. ) Using the truth tables Scenario: Calculate a bonus for a salesperson Bonus condition: “A” rating and sales > $9, 000 Appropriate operators: And, And. Also (more efficient) Both conditions must be true to receive bonus Sample code: str. Rating = "A” And. Also dbl. Sales > 9000 36 Programming with Microsoft Visual Basic 2010, 5 th Edition

Logical Operators (cont’d. ) Using logical operators: Calculating gross pay 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 Data validation Verifying that input data is within expected range 37 Programming with Microsoft Visual Basic 2010, 5 th Edition

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 38 Programming with Microsoft Visual Basic 2010, 5 th Edition

Figure 4 -28 Examples of using string comparisons in a procedure 39 Programming with Microsoft Visual Basic 2010, 5 th Edition

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 uppercase To. Lower method: Converts string to lowercase Syntax and examples shown in Figure 4 -29 on next two slides 40 Programming with Microsoft Visual Basic 2010, 5 th Edition

Figure 4 -29 Syntax and examples of the To. Upper and To. Lower methods (continues) 41 Programming with Microsoft Visual Basic 2010, 5 th Edition

Figure 4 -29 Syntax and examples of the To. Upper and To. Lower methods (cont’d. ) 42 Programming with Microsoft Visual Basic 2010, 5 th Edition

to Uppercase or Lowercase (cont’d. ) 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 text box’s value converted to uppercase 43 Programming with Microsoft Visual Basic 2010, 5 th Edition

Figure 4 -29 Examples of using the To. Upper and To. Lower methods in a procedure 44 Programming with Microsoft Visual Basic 2010, 5 th Edition

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 in Figure 4 -32 on next slide 45 Programming with Microsoft Visual Basic 2010, 5 th Edition

Comparing Boolean Values (cont’d. ) Figure 4 -32 Examples of using Boolean values in a condition 46 Programming with Microsoft Visual Basic 2010, 5 th Edition

Comparing Boolean Values (cont’d. ) Comparing Boolean values: 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 47 Programming with Microsoft Visual Basic 2010, 5 th Edition

Figure 4 -33 Syntax and example of using the Boolean value returned by the Try. Parse method 48 Programming with Microsoft Visual Basic 2010, 5 th Edition

Summary of Operators Precedence of logical operators Evaluated after any arithmetic or comparison operators in the expression Summary listing of arithmetic, concatenation, comparison, and logical operators in Figure 4 -36 in text 49 Programming with Microsoft Visual Basic 2010, 5 th Edition

Lesson A Summary Single and dual-alternative selection structures Use If. . . Then. . . Else statement 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 Use text box’s Character. Casing property to change text to upper- or lowercase 50 Programming with Microsoft Visual Basic 2010, 5 th Edition

Lesson A Summary (cont’d. ) 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 Arithmetic operators are evaluated first, then comparison operators, and finally logical operators 51 Programming with Microsoft Visual Basic 2010, 5 th Edition

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 52 Programming with Microsoft Visual Basic 2010, 5 th Edition

Creating the Monthly Payment Calculator Application Program requirement Calculate monthly payment on car loan Application needs The loan amount (principal) The annual percentage rate (APR) of interest The life of the loan (term) in years 53 Programming with Microsoft Visual Basic 2010, 5 th Edition

Creating the Monthly Payment Calculator Application (cont’d. ) 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 54 Programming with Microsoft Visual Basic 2010, 5 th Edition

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 55 Programming with Microsoft Visual Basic 2010, 5 th Edition

Figure 4 -42 TOE chart for the Monthly Payment Calculator application 56 Programming with Microsoft Visual Basic 2010, 5 th Edition

Coding the Monthly Payment Calculator Application (cont’d. ) Coding the btn. Calc control’s Click event procedure Calculate monthly payment amount Display result in lbl. Payment control Determine need for named constants and variables Constants: Items that do not change each time procedure invoked Variables: Items will likely change each time 57 Programming with Microsoft Visual Basic 2010, 5 th Edition

Coding the Monthly Payment Calculator Application (cont’d. ) Figure 4 -43 Pseudocode for the btn. Calc control’s Click event procedure 58 Programming with Microsoft Visual Basic 2010, 5 th Edition

Figure 4 -44 Partially completed Click event procedure 59 Programming with Microsoft Visual Basic 2010, 5 th Edition

Using the Financial. Pmt Method 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 annual interest rate to monthly rate by dividing by 12 Convert annual term to monthly term by multiplying by 12 60 Programming with Microsoft Visual Basic 2010, 5 th Edition

Figure 4 -45 Basic syntax and examples of the Financial. Pmt method 61 Programming with Microsoft Visual Basic 2010, 5 th Edition

Using the Financial. Pmt Method (cont’d. ) Figure 4 -46 Selection structure’s true path coded in the procedure 62 Programming with Microsoft Visual Basic 2010, 5 th Edition

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 63 Programming with Microsoft Visual Basic 2010, 5 th Edition

The Message. Box. Show Method (cont’d. ) Figure 4 -50 Values returned by the Message. Box. Show method (continues) 64 Programming with Microsoft Visual Basic 2010, 5 th Edition

The Message. Box. Show Method (cont’d. ) Figure 4 -50 Values returned by the Message. Box. Show method (cont’d. ) 65 Programming with Microsoft Visual Basic 2010, 5 th Edition

Lesson B Summary Group box: A container control that treats its contents as one unit Use Group. Box tool to add a group box 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 66 Programming with Microsoft Visual Basic 2010, 5 th Edition

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 67 Programming with Microsoft Visual Basic 2010, 5 th Edition

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 68 Programming with Microsoft Visual Basic 2010, 5 th Edition

Figure 4 -57 Examples of using the Key. Char and Handled properties in the Key. Press event procedure 69 Programming with Microsoft Visual Basic 2010, 5 th Edition

Coding the Key. Press Event Procedures (cont’d. ) Figure 4 -58 Cancel. Keys procedure 70 Programming with Microsoft Visual Basic 2010, 5 th Edition

Coding the Enter Event Procedures 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 71 Programming with Microsoft Visual Basic 2010, 5 th Edition

Coding the Enter Event Procedures (cont’d. ) Figure 4 -59 Syntax and an example of the Select. All method 72 Programming with Microsoft Visual Basic 2010, 5 th Edition

Lesson C Summary Key. Press event occurs when user presses key Use Key. Press event to cancel unwanted key pressed by user Use Select. All method to select all contents of text box Enter event occurs when text box receives focus Use Enter event to process code when control receives focus 73 Programming with Microsoft Visual Basic 2010, 5 th Edition
- Slides: 73