Presentation is loading. Please wait.

Presentation is loading. Please wait.

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

Similar presentations


Presentation on theme: "Chapter Four The Selection Structure Programming with Microsoft Visual Basic 2010 5 th Edition."— Presentation transcript:

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

2 Previewing the Monthly Payment Calculator Application 2 The Monthly Payment Calculator application uses the selection structure

3 3 Figure 4-2 Monthly payment amount shown in the interface Figure 4-1 Message box

4 Lesson A Objectives 4 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 TryParse method

5 Making Decisions in a Program 5 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

6 Making Decisions in a Program (cont’d.) 6 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

7 Making Decisions in a Program (cont’d.) 7 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

8 Making Decisions in a Program (cont’d.) 8 Figure 4-3 Selection structures you might use today

9 Making Decisions in a Program (cont’d.) 9 Example: Kanton Boutique Figure 4-4 Problem specification for Kanton Boutique

10 10 Figure 4-6 Pseudocode containing only the sequence structure Figure 4-5 Interface for the Kanton Boutique application

11 11 Figure 4-7 Modified problem specification and pseudocode containing a single-alternative selection structure

12 Making Decisions in a Program (cont’d.) 12 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

13 13 Figure 4-8 Single-alternative selection structure shown in a flowchart

14 14 Figure 4-9 Modified problem specification and pseudocode containing a dual-alternative selection structure

15 15 Figure 4-10 Dual-alternative selection structure shown in a flowchart

16 Coding Single-Alternative and Dual- Alternative Selection Structures 16 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

17 17 Figure 4-11 Syntax and examples of the If…Then…Else statement (continues)

18 18 Figure 4-11 Syntax and examples of the If…Then…Else statement (cont’d.)

19 Comparison Operators 19 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

20 20 Figure 4-12 Listing and examples of commonly used comparison operators

21 Comparison Operators (cont’d.) 21 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

22 Comparison Operators (cont’d.) 22 Figure 4-15 Pseudocode containing a single-alternative selection structure

23 23 Figure 4-16 Flowchart containing a single-alternative selection structure

24 24 Figure 4-17 Display button’s Click event procedure

25 Comparison Operators (cont’d.) 25 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

26 Comparison Operators (cont’d.) 26 Figure 4-18 Illustration of the swapping concept

27 Comparison Operators (cont’d.) 27 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

28 Comparison Operators (cont’d.) 28 Figure 4-20 Pseudocode containing a dual-alternative selection structure

29 29 Figure 4-21 Pseudocode containing a dual-alternative selection structure

30 30 Figure 4-22 Calculate button’s Click event procedure

31 Logical Operators 31 Logical operators Used to create compound conditions Expressions evaluate to a Boolean value True or False Six logical operators in Visual Basic Not, And, AndAlso, Or, OrElse, Xor

32 32 Figure 4-23 Listing and examples of logical operators (continues)

33 33 Figure 4-23 Listing and examples of logical operators (cont’d.)

34 Logical Operators (cont’d.) 34 Truth tables Show how logical operators are evaluated Short-circuit evaluation Bypasses evaluation of condition when outcome can be determined without it Operators using technique: AndAlso, OrElse Example: If state = "TN" AndAlso sales > $5000 Then… If state is not TN, no need to evaluate sales > $5000

35 35 Figure 4-24 Truth tables for the logical operators

36 Logical Operators (cont’d.) 36 Using the truth tables Scenario: Calculate a bonus for a salesperson Bonus condition: “A” rating and sales > $9,000 Appropriate operators: And, AndAlso (more efficient) Both conditions must be true to receive bonus Sample code: strRating = "A” AndAlso dblSales > 9000

37 Logical Operators (cont’d.) 37 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 AndAlso or OrElse Data validation Verifying that input data is within expected range

38 Comparing Strings Containing Letters 38 Scenario: Display “Pass” if ‘P’ is entered in txtLetter control Display “Fail” if ‘F’ is entered in txtLetter control Can use the OrElse or the AndAlso operator Note that ‘P’ is not the same as ‘p’ They have different Unicode values

39 39 Figure 4-28 Examples of using string comparisons in a procedure

40 Converting a String to Uppercase or Lowercase 40 String comparisons are case sensitive CharacterCasing property: Three case values: Normal (default), Upper, Lower ToUpper method: Converts string to uppercase ToLower method: Converts string to lowercase Syntax and examples shown in Figure 4-29 on next two slides

41 41 Figure 4-29 Syntax and examples of the ToUpper and ToLower methods (continues)

42 42 Figure 4-29 Syntax and examples of the ToUpper and ToLower methods (cont’d.)

43 Converting a String to Uppercase or Lowercase (cont’d.) 43 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 Must handle case variations in the user’s input Can use ToLower or ToUpper Can assign a String variable to the input text box’s value converted to uppercase

44 44 Figure 4-29 Examples of using the ToUpper and ToLower methods in a procedure

45 Comparing Boolean Values 45 Boolean variable: Contains either True or False Naming convention: “Is” denotes Boolean type Example: blnIsInsured When testing for a True value, it is not necessary to include the “= True” Examples in Figure 4-32 on next slide

46 Comparing Boolean Values (cont’d.) 46 Figure 4-32 Examples of using Boolean values in a condition

47 Comparing Boolean Values (cont’d.) 47 Comparing Boolean values: Determining whether a string can be converted to a number TryParse method returns a numeric value after converting the string, or 0 if it cannot be converted TryParse also returns a Boolean value indicating success or failure of the conversion attempt Use Boolean value returned by TryParse method in an If…Then…Else statement

48 48 Figure 4-33 Syntax and example of using the Boolean value returned by the TryParse method

49 Summary of Operators 49 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

50 Lesson A Summary 50 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 CharacterCasing property to change text to upper- or lowercase

51 Lesson A Summary (cont’d.) 51 Use ToUpper and ToLower to temporarily modify the case of input text Use Boolean return value of TryParse method to determine whether string was successfully converted to numeric value Arithmetic operators are evaluated first, then comparison operators, and finally logical operators

52 Lesson B Objectives 52 After studying Lesson B, you should be able to: 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

53 Creating the Monthly Payment Calculator Application 53 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

54 Creating the Monthly Payment Calculator Application (cont’d.) 54 Adding a group box to the form Group box: Container control for other controls GroupBox 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 TabIndex after placement of controls

55 Coding the Monthly Payment Calculator Application 55 Procedures required according to TOE chart Click event procedure code for the two buttons Code for TextChanged, KeyPress, and Enter events for text boxes Procedures that are already coded btnExit Click event and TextChanged events for the text boxes Procedure to code in Lesson B btnCalc button’s Click event procedure

56 56 Figure 4-42 TOE chart for the Monthly Payment Calculator application

57 Coding the Monthly Payment Calculator Application (cont’d.) 57 Coding the btnCalc control’s Click event procedure Calculate monthly payment amount Display result in lblPayment 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

58 Coding the Monthly Payment Calculator Application (cont’d.) 58 Figure 4-43 Pseudocode for the btnCalc control’s Click event procedure

59 59 Figure 4-44 Partially completed Click event procedure

60 Using the Financial.Pmt Method 60 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

61 61 Figure 4-45 Basic syntax and examples of the Financial.Pmt method

62 Using the Financial.Pmt Method (cont’d.) 62 Figure 4-46 Selection structure’s true path coded in the procedure

63 The MessageBox.Show Method 63 MessageBox.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

64 The MessageBox.Show Method (cont’d.) 64 Figure 4-50 Values returned by the MessageBox.Show method (continues)

65 The MessageBox.Show Method (cont’d.) 65 Figure 4-50 Values returned by the MessageBox.Show method (cont’d.)

66 Lesson B Summary 66 Group box: A container control that treats its contents as one unit Use GroupBox tool to add a group box Use Financial.Pmt method to calculate loan or investment payments MessageBox.Show method displays message box with text, one or more buttons, and icon

67 Lesson C Objectives 67 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

68 Coding the KeyPress Event Procedures 68 KeyPress event Occurs when key is pressed while control has focus Character corresponding to pressed key is sent to KeyPress event’s e parameter KeyPress event can be used to prevent users from entering inappropriate characters Use e parameter’s KeyChar property to determine pressed key Use Handled property to cancel key if needed

69 69 Figure 4-57 Examples of using the KeyChar and Handled properties in the KeyPress event procedure

70 Coding the KeyPress Event Procedures (cont’d.) 70 Figure 4-58 CancelKeys procedure

71 Coding the Enter Event Procedures 71 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 SelectAll method Selects all text contained in text box Add to each text box’s Enter event procedure

72 Coding the Enter Event Procedures (cont’d.) 72 Figure 4-59 Syntax and an example of the SelectAll method

73 Lesson C Summary 73 KeyPress event occurs when user presses key Use KeyPress event to cancel unwanted key pressed by user Use SelectAll 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


Download ppt "Chapter Four The Selection Structure Programming with Microsoft Visual Basic 2010 5 th Edition."

Similar presentations


Ads by Google