54
Chapter 4: The Selection Structure Programming with Microsoft Visual Basic 2005, Third Edition

Chapter 4: The Selection Structure

  • Upload
    norm

  • View
    56

  • Download
    2

Embed Size (px)

DESCRIPTION

Chapter 4: The Selection Structure. Programming with Microsoft Visual Basic 2005, Third Edition. 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 - PowerPoint PPT Presentation

Citation preview

Page 1: Chapter 4: The Selection Structure

Chapter 4: The Selection Structure

Programming with Microsoft Visual Basic 2005, Third Edition

Page 2: Chapter 4: The Selection Structure

2Programming with Microsoft Visual Basic 2005, Third Edition

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

Page 3: Chapter 4: The Selection Structure

3Programming 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

Page 4: Chapter 4: The Selection Structure

4Programming 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

Page 5: Chapter 4: The Selection Structure

5Programming 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

Page 6: Chapter 4: The Selection Structure

6Programming 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

Page 7: Chapter 4: The Selection Structure

7Programming 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

Page 8: Chapter 4: The Selection Structure

8Programming 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

Page 9: Chapter 4: The Selection Structure

9Programming 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

Page 10: Chapter 4: The Selection Structure

10Programming 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

Page 11: Chapter 4: The Selection Structure

11Programming with Microsoft Visual Basic 2005, Third Edition

Comparison Operators (continued)

Figure 4-7: Listing and examples of commonly used comparison operators (continued)

Page 12: Chapter 4: The Selection Structure

12Programming with Microsoft Visual Basic 2005, Third Edition

Comparison Operators (continued)

Figure 4-7: Listing and examples of commonly used comparison operators

Page 13: Chapter 4: The Selection Structure

13Programming 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

Page 14: Chapter 4: The Selection Structure

14Programming 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

Page 15: Chapter 4: The Selection Structure

15Programming 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

Page 16: Chapter 4: The Selection Structure

16Programming 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

Page 17: Chapter 4: The Selection Structure

17Programming 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

Page 18: Chapter 4: The Selection Structure

18Programming with Microsoft Visual Basic 2005, Third Edition

Logical Operators (continued)

Figure 4-18: Listing and examples of logical operators (partial)

Page 19: Chapter 4: The Selection Structure

Logical Operators (continued)

• Truth table for Not operator

If condition is Value of Result is

True False

False True

Result = Not Condition

Page 20: Chapter 4: The Selection Structure

Logical Operators (continued)

• Truth table for And operator

If condition1 is And condition2 is Value of Result is

True True True

True False False

False True False

False False False

Result = condition1 And Condition2

Page 21: Chapter 4: The Selection Structure

Logical Operators (continued)

• Truth table for AndAlso operator

If condition1 is And condition2 is Value of Result is

True True True

True False False

False (not evaluated) False

Result = condition1 AndAlso Condition2

Page 22: Chapter 4: The Selection Structure

Logical Operators (continued)

• Truth table for Or operator

If condition1 is And condition2 is Value of Result is

True True True

True False True

False True True

False False False

Result = condition1 Or Condition2

Page 23: Chapter 4: The Selection Structure

Logical Operators (continued)

• Truth table for OrElse operator

If condition1 is And condition2 is Value of Result is

True (not evaluated) True

False True True

False False False

Result = condition1 OrElse Condition2

Page 24: Chapter 4: The Selection Structure

Logical Operators (continued)

• Truth table for Xor operator

If condition1 is And condition2 is Value of Result is

True True False

True False True

False True True

False False False

Result = condition1 Xor Condition2

Page 25: Chapter 4: The Selection Structure

25Programming 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

Page 26: Chapter 4: The Selection Structure

26Programming with Microsoft Visual Basic 2005, Third Edition

Using Truth Tables (continued)

Figure 4-20: Order of precedence for arithmetic, comparison, and logical operators

Page 27: Chapter 4: The Selection Structure

27Programming 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

Page 28: Chapter 4: The Selection Structure

28Programming 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)

Page 29: Chapter 4: The Selection Structure

29Programming 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

Page 30: Chapter 4: The Selection Structure

30Programming 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

Page 31: Chapter 4: The Selection Structure

31Programming 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

Page 32: Chapter 4: The Selection Structure

32Programming 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

Page 33: Chapter 4: The Selection Structure

33Programming 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

Page 34: Chapter 4: The Selection Structure

34Programming with Microsoft Visual Basic 2005, Third Edition

Comparing Boolean Values (continued)

Figure 4-29: Syntax and examples of the String.IsNullOrEmpty method

Page 35: Chapter 4: The Selection Structure

35Programming 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

Page 36: Chapter 4: The Selection Structure

36Programming 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

Page 37: Chapter 4: The Selection Structure

37Programming 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

Page 38: Chapter 4: The Selection Structure

38Programming 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

Page 39: Chapter 4: The Selection Structure

39Programming with Microsoft Visual Basic 2005, Third Edition

Completing the User Interface (continued)

Figure 4-34: Sketch of the Monthly Payment Calculator user interface

Page 40: Chapter 4: The Selection Structure

40Programming 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

Page 41: Chapter 4: The Selection Structure

41Programming 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

Page 42: Chapter 4: The Selection Structure

42Programming 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

Page 43: Chapter 4: The Selection Structure

43Programming 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

Page 44: Chapter 4: The Selection Structure

44Programming 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

Page 45: Chapter 4: The Selection Structure

45Programming 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

Page 46: Chapter 4: The Selection Structure

46Programming with Microsoft Visual Basic 2005, Third Edition

The MessageBox.Show Method (continued)

Figure 4-48: Completed xCalcButton’s Click event procedure

Page 47: Chapter 4: The Selection Structure

47Programming with Microsoft Visual Basic 2005, Third Edition

The MessageBox.Show Method (continued)

Figure 4-50: Message box created by the MessageBox.Show method

Page 48: Chapter 4: The Selection Structure

48Programming 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

Page 49: Chapter 4: The Selection Structure

49Programming 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

Page 50: Chapter 4: The Selection Structure

50Programming 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

Page 51: Chapter 4: The Selection Structure

51Programming with Microsoft Visual Basic 2005, Third Edition

Coding the KeyPress Event Procedures (continued)

Figure 4-54: Completed CancelKeys procedure

Page 52: Chapter 4: The Selection Structure

52Programming 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

Page 53: Chapter 4: The Selection Structure

53Programming with Microsoft Visual Basic 2005, Third Edition

Coding the Enter Event Procedure (continued)

Figure 4-57: Existing text selected in the xPrincipalTextBox

Page 54: Chapter 4: The Selection Structure

54Programming 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