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

Programming with Microsoft Visual Basic 2010 5 th Edition

Embed Size (px)

DESCRIPTION

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. Figure 4-1 Message box. Figure 4-2 - PowerPoint PPT Presentation

Citation preview

Page 1: Programming with  Microsoft Visual Basic 2010  5 th  Edition

Chapter FourThe Selection Structure

Programming with Microsoft Visual Basic 2010

5th Edition

Page 2: Programming with  Microsoft Visual Basic 2010  5 th  Edition

Previewing the Monthly Payment Calculator Application

2

The Monthly Payment Calculator application uses the selection structure

Page 3: Programming with  Microsoft Visual Basic 2010  5 th  Edition

3

Figure 4-2 Monthly payment amount

shown in the interface

Figure 4-1 Message box

Page 4: Programming with  Microsoft Visual Basic 2010  5 th  Edition

Lesson A Objectives

4

After studying Lesson A, you should be able to: Write pseudocode for the selection structureCreate a flowchart to help you plan an

application’s codeWrite an If...Then...Else statementInclude comparison operators and logical

operators in a selection structure’s conditionChange the case of a stringDetermine the success of the TryParse method

Page 5: Programming with  Microsoft Visual Basic 2010  5 th  Edition

Making Decisions in a Program

5

Three basic control structuresSequenceSelectionRepetition

All procedures in an application are written using one of more of these structuresProcedures in previous chapters used

sequence structure only

Page 6: Programming with  Microsoft Visual Basic 2010  5 th  Edition

Making Decisions in a Program (cont’d.)

6

Selection structure Chooses one of two paths based on conditionAlso called a decision structure

Example:If employee works over 40 hours, add

overtime payCondition

Decision expression evaluating to true or false

Page 7: Programming with  Microsoft Visual Basic 2010  5 th  Edition

Making Decisions in a Program (cont’d.)

7

Single-alternative selection structureTasks performed only when condition is true

Dual-alternative selection structureOne set of tasks performed if condition is true

Called true pathDifferent set of tasks performed if condition is

falseCalled false path

If and end if Denotes selection structure’s beginning and end

Else denotes beginning of false path

Page 8: Programming with  Microsoft Visual Basic 2010  5 th  Edition

Making Decisions in a Program (cont’d.)

8

Figure 4-3 Selection structures you might use today

Page 9: Programming with  Microsoft Visual Basic 2010  5 th  Edition

Making Decisions in a Program (cont’d.)

9

Example: Kanton Boutique

Figure 4-4 Problem specification for Kanton Boutique

Page 10: Programming with  Microsoft Visual Basic 2010  5 th  Edition

10

Figure 4-6 Pseudocode containing only the sequence structure

Figure 4-5 Interface for the Kanton Boutique application

Page 11: Programming with  Microsoft Visual Basic 2010  5 th  Edition

11

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

Page 12: Programming with  Microsoft Visual Basic 2010  5 th  Edition

Making Decisions in a Program (cont’d.)

12

Decision symbolDiamond shape in a flowchartRepresents the selection structure’s condition

Other symbolsOval: Start/stop symbolRectangle: Process symbolParallelogram: Input/output symbol

Page 13: Programming with  Microsoft Visual Basic 2010  5 th  Edition

13

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

Page 14: Programming with  Microsoft Visual Basic 2010  5 th  Edition

14

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

Page 15: Programming with  Microsoft Visual Basic 2010  5 th  Edition

15

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

Page 16: Programming with  Microsoft Visual Basic 2010  5 th  Edition

Coding Single-Alternative and Dual-Alternative Selection Structures

16

If…Then…Else statementUsed to code single and dual-alternative

selection structuresStatement block

Set of statements in each pathSyntax and examples shown in Figure 4-11

on next slide

Page 17: Programming with  Microsoft Visual Basic 2010  5 th  Edition

17

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

Page 18: Programming with  Microsoft Visual Basic 2010  5 th  Edition

18

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

Page 19: Programming with  Microsoft Visual Basic 2010  5 th  Edition

Comparison Operators

19

Comparison operatorsUsed to compare two valuesAlways result in a True or False value

Rules for comparison operatorsThey do not have an order of precedenceThey are evaluated from left to rightThey are evaluated after any arithmetic

operators in the expression

Page 20: Programming with  Microsoft Visual Basic 2010  5 th  Edition

20

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

Page 21: Programming with  Microsoft Visual Basic 2010  5 th  Edition

Comparison Operators (cont’d.)

21

Using comparison operators: Swapping numeric valuesSample application displays the lowest and

highest of two numbers entered by the user

Figure 4-14 Sample run of the Lowest and Highest

application

Page 22: Programming with  Microsoft Visual Basic 2010  5 th  Edition

Comparison Operators (cont’d.)

22

Figure 4-15 Pseudocode containing a single-alternative selection structure

Page 23: Programming with  Microsoft Visual Basic 2010  5 th  Edition

23

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

Page 24: Programming with  Microsoft Visual Basic 2010  5 th  Edition

24

Figure 4-17 Display button’s Click event procedure

Page 25: Programming with  Microsoft Visual Basic 2010  5 th  Edition

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 swappedDeclared within statement blockBlock-level variable

Block scopeRestricts use of variable to statement block

in which it is declared

Page 26: Programming with  Microsoft Visual Basic 2010  5 th  Edition

Comparison Operators (cont’d.)

26

Figure 4-18 Illustration of the swapping concept

Page 27: Programming with  Microsoft Visual Basic 2010  5 th  Edition

Comparison Operators (cont’d.)

27

Using comparison operators: Displaying the sum or differenceSample application displays the sum or

difference of two numbers entered by the user

Figure 4-19 Sample run of the Addition and Subtraction application

Page 28: Programming with  Microsoft Visual Basic 2010  5 th  Edition

Comparison Operators (cont’d.)

28

Figure 4-20 Pseudocode containing a dual-alternative selection structure

Page 29: Programming with  Microsoft Visual Basic 2010  5 th  Edition

29

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

Page 30: Programming with  Microsoft Visual Basic 2010  5 th  Edition

30

Figure 4-22 Calculate button’s Click event procedure

Page 31: Programming with  Microsoft Visual Basic 2010  5 th  Edition

Logical Operators

31

Logical operatorsUsed to create compound conditionsExpressions evaluate to a Boolean value

True or False

Six logical operators in Visual BasicNot, And, AndAlso, Or, OrElse, Xor

Page 32: Programming with  Microsoft Visual Basic 2010  5 th  Edition

32

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

Page 33: Programming with  Microsoft Visual Basic 2010  5 th  Edition

33

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

Page 34: Programming with  Microsoft Visual Basic 2010  5 th  Edition

Logical Operators (cont’d.)

34

Truth tablesShow how logical operators are evaluated

Short-circuit evaluationBypasses evaluation of condition when

outcome can be determined without itOperators using technique: AndAlso, OrElse

Example: If state = "TN" AndAlso sales > $5000 Then…If state is not TN, no need to evaluate sales >

$5000

Page 35: Programming with  Microsoft Visual Basic 2010  5 th  Edition

35

Figure 4-24 Truth tables for the logical

operators

Page 36: Programming with  Microsoft Visual Basic 2010  5 th  Edition

Logical Operators (cont’d.)

36

Using the truth tablesScenario: Calculate a bonus for a salesperson

Bonus condition: “A” rating and sales > $9,000Appropriate operators: And, AndAlso (more efficient)Both conditions must be true to receive bonusSample code: strRating = "A” AndAlso dblSales > 9000

Page 37: Programming with  Microsoft Visual Basic 2010  5 th  Edition

Logical Operators (cont’d.)

37

Using logical operators: Calculating gross payScenario: Calculate and display employee gross

payRequirements for application

Verify hours are within range (>= 0.0 and <= 40.0)If data is valid, calculate and display gross payIf data is not valid, display error message

Can accomplish this using AndAlso or OrElseData validation

Verifying that input data is within expected range

Page 38: Programming with  Microsoft Visual Basic 2010  5 th  Edition

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 operatorNote that ‘P’ is not the same as ‘p’

They have different Unicode values

Page 39: Programming with  Microsoft Visual Basic 2010  5 th  Edition

39

Figure 4-28

Examples of using string comparisons in a

procedure

Page 40: Programming with  Microsoft Visual Basic 2010  5 th  Edition

Converting a String to Uppercase or Lowercase

40

String comparisons are case sensitiveCharacterCasing 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

Page 41: Programming with  Microsoft Visual Basic 2010  5 th  Edition

41

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

Page 42: Programming with  Microsoft Visual Basic 2010  5 th  Edition

42

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

Page 43: Programming with  Microsoft Visual Basic 2010  5 th  Edition

Converting a String to Uppercase or Lowercase (cont’d.)

43

Using the ToUpper and ToLower Methods: Displaying a MessageProcedure requirements

Display message “We have a store in this state”Valid states: IL, IN, KYMust handle case variations in the user’s input

Can use ToLower or ToUpperCan assign a String variable to the input

text box’s value converted to uppercase

Page 44: Programming with  Microsoft Visual Basic 2010  5 th  Edition

44

Figure 4-29 Examples of using the ToUpper and ToLower

methods in a procedure

Page 45: Programming with  Microsoft Visual Basic 2010  5 th  Edition

Comparing Boolean Values

45

Boolean variable: Contains either True or False

Naming convention: “Is” denotes Boolean typeExample: blnIsInsured

When testing for a True value, it is not necessary to include the “= True”Examples in Figure 4-32 on next slide

Page 46: Programming with  Microsoft Visual Basic 2010  5 th  Edition

Comparing Boolean Values (cont’d.)

46

Figure 4-32 Examples of using Boolean values in a condition

Page 47: Programming with  Microsoft Visual Basic 2010  5 th  Edition

Comparing Boolean Values (cont’d.)

47

Comparing Boolean values: Determining whether a string can be converted to a numberTryParse 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

Page 48: Programming with  Microsoft Visual Basic 2010  5 th  Edition

48

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

Page 49: Programming with  Microsoft Visual Basic 2010  5 th  Edition

Summary of Operators

49

Precedence of logical operatorsEvaluated after any arithmetic or comparison

operators in the expressionSummary listing of arithmetic,

concatenation, comparison, and logical operators in Figure 4-36 in text

Page 50: Programming with  Microsoft Visual Basic 2010  5 th  Edition

Lesson A Summary

50

Single and dual-alternative selection structuresUse 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

Page 51: Programming with  Microsoft Visual Basic 2010  5 th  Edition

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

Page 52: Programming with  Microsoft Visual Basic 2010  5 th  Edition

Lesson B Objectives

52

After studying Lesson B, you should be able to:

Group objects using a GroupBox controlCalculate a periodic payment using the

Financial.Pmt methodCreate a message box using the

MessageBox.Show methodDetermine the value returned by a

message box

Page 53: Programming with  Microsoft Visual Basic 2010  5 th  Edition

Creating the Monthly Payment Calculator Application

53

Program requirementCalculate monthly payment on car loanApplication needs

The loan amount (principal)The annual percentage rate (APR) of interestThe life of the loan (term) in years

Page 54: Programming with  Microsoft Visual Basic 2010  5 th  Edition

Creating the Monthly Payment Calculator Application (cont’d.)

54

Adding a group box to the formGroup box: Container control for other controls

GroupBox tool: Used to add group box control to interface

Group box control provides:Visual separation of related controlsAbility to manage the grouped controls by

manipulating the group box controlLock controls to ensure that they are not movedBe sure to set TabIndex after placement of

controls

Page 55: Programming with  Microsoft Visual Basic 2010  5 th  Edition

Coding the Monthly Payment Calculator Application

55

Procedures required according to TOE chartClick event procedure code for the two

buttons Code for TextChanged, KeyPress, and Enter

events for text boxesProcedures that are already coded

btnExit Click event and TextChanged events for the text boxes

Procedure to code in Lesson BbtnCalc button’s Click event procedure

Page 56: Programming with  Microsoft Visual Basic 2010  5 th  Edition

56

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

Page 57: Programming with  Microsoft Visual Basic 2010  5 th  Edition

Coding the Monthly Payment Calculator Application (cont’d.)

57

Coding the btnCalc control’s Click event procedureCalculate monthly payment amountDisplay result in lblPayment control

Determine need for named constants and variables Constants: Items that do not change each

time procedure invokedVariables: Items will likely change each time

Page 58: Programming with  Microsoft Visual Basic 2010  5 th  Edition

Coding the Monthly Payment Calculator Application (cont’d.)

58

Figure 4-43 Pseudocode for the btnCalc control’s Click event procedure

Page 59: Programming with  Microsoft Visual Basic 2010  5 th  Edition

59

Figure 4-44 Partially completed Click event procedure

Page 60: Programming with  Microsoft Visual Basic 2010  5 th  Edition

Using the Financial.Pmt Method

60

Financial.Pmt methodCalculates periodic payment on loan or

investmentMust 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 12Convert annual term to monthly term by multiplying

by 12

Page 61: Programming with  Microsoft Visual Basic 2010  5 th  Edition

61

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

Page 62: Programming with  Microsoft Visual Basic 2010  5 th  Edition

Using the Financial.Pmt Method (cont’d.)

62

Figure 4-46 Selection structure’s true path coded in the procedure

Page 63: Programming with  Microsoft Visual Basic 2010  5 th  Edition

The MessageBox.Show Method

63

MessageBox.show methodDisplays message box with text message,

caption, button(s), and iconUse sentence capitalization for text

messageUse book title capitalization for captionIcons

Exclamation or question: Indicates user must make a decision before continuing

Information: Indicates informational messageStop: Indicates serious problem

Page 64: Programming with  Microsoft Visual Basic 2010  5 th  Edition

The MessageBox.Show Method (cont’d.)

64

Figure 4-50 Values returned by the MessageBox.Show method (continues)

Page 65: Programming with  Microsoft Visual Basic 2010  5 th  Edition

The MessageBox.Show Method (cont’d.)

65

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

Page 66: Programming with  Microsoft Visual Basic 2010  5 th  Edition

Lesson B Summary

66

Group box: A container control that treats its contents as one unitUse 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

Page 67: Programming with  Microsoft Visual Basic 2010  5 th  Edition

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

Page 68: Programming with  Microsoft Visual Basic 2010  5 th  Edition

Coding the KeyPress Event Procedures

68

KeyPress eventOccurs 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 charactersUse e parameter’s KeyChar property to

determine pressed keyUse Handled property to cancel key if

needed

Page 69: Programming with  Microsoft Visual Basic 2010  5 th  Edition

69

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

Page 70: Programming with  Microsoft Visual Basic 2010  5 th  Edition

Coding the KeyPress Event Procedures (cont’d.)

70

Figure 4-58 CancelKeys procedure

Page 71: Programming with  Microsoft Visual Basic 2010  5 th  Edition

Coding the Enter Event Procedures

71

Enter eventOccurs when text box receives focusIf text is selected, user can replace existing

text by pressing keyCan use Enter event to select all of text

SelectAll methodSelects all text contained in text boxAdd to each text box’s Enter event procedure

Page 72: Programming with  Microsoft Visual Basic 2010  5 th  Edition

Coding the Enter Event Procedures (cont’d.)

72

Figure 4-59 Syntax and an example of the SelectAll method

Page 73: Programming with  Microsoft Visual Basic 2010  5 th  Edition

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