Programming with microsoft visual basic 2008 fourth edition
Download
1 / 69

Chapter 4 - PowerPoint PPT Presentation


  • 266 Views
  • Updated On :

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 Previewing the Monthly Payment Calculator Application (continued)

loader
I am the owner, or an agent authorized to act on behalf of the owner, of the copyrighted work described.
capcha
Download Presentation

PowerPoint Slideshow about 'Chapter 4' - omer


An Image/Link below is provided (as is) to download presentation

Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author.While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server.


- - - - - - - - - - - - - - - - - - - - - - - - - - E N D - - - - - - - - - - - - - - - - - - - - - - - - - -
Presentation Transcript
Programming with microsoft visual basic 2008 fourth edition l.jpg

Programming with Microsoft Visual Basic 2008 Fourth Edition

Chapter Four

The Selection Structure


Previewing the monthly payment calculator application l.jpg
Previewing the Monthly Payment Calculator Application

  • The Monthly Payment Calculator application uses the selection structure

Programming with Microsoft Visual Basic 2008, Fourth Edition


Previewing the monthly payment calculator application continued l.jpg
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


Lesson a objectives l.jpg
Lesson A Objectives (continued)

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 TryParse method

Programming with Microsoft Visual Basic 2008, Fourth Edition


The selection structure l.jpg
The Selection Structure (continued)

  • 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, If/ElseIf/Else, and Case

Programming with Microsoft Visual Basic 2008, Fourth Edition


The selection structure continued l.jpg
The Selection Structure (continued) (continued)

Figure 4-3: Selection structures you might use today

Programming with Microsoft Visual Basic 2008, Fourth Edition


Writing pseudocode for if and if else selection structures l.jpg
Writing Pseudocode for If (continued)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


Writing pseudocode for if and if else selection structures continued l.jpg
Writing Pseudocode for If (continued)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


Flowcharting the if and if else selection structures l.jpg
Flowcharting the If and If/Else Selection Structures (continued)

  • 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


Coding the if and if else selection structures l.jpg
Coding the If and (continued)If/Else Selection Structures

  • If…Then…Else statement: Usedto 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


Flowcharting the if and if else selection structures continued l.jpg
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


Comparison operators l.jpg
Comparison Operators (continued)

  • Comparison (relational) operators:

    • Used to test two items for equality or types of non-equality

    • 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


Comparison operators continued l.jpg
Comparison Operators (continued) (continued)

Figure 4-8: Evaluation steps for an expression containing arithmetic and comparison operators

Programming with Microsoft Visual Basic 2008, Fourth Edition


Slide14 l.jpg

Using Comparison Operators—Swapping Numeric Values (continued)

  • Sample application displays the lowest and highest of two numbers entered by the user

Programming with Microsoft Visual Basic 2008, Fourth Edition


Slide15 l.jpg

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


Slide16 l.jpg

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


Slide17 l.jpg

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


Slide18 l.jpg

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


Using comparison operators swapping numeric values continued l.jpg
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


Using comparison operators swapping numeric values continued20 l.jpg
Using Comparison Operators—Swapping Numeric Values (continued)

Figure 4-13: Illustration of the swapping concept

Programming with Microsoft Visual Basic 2008, Fourth Edition


Using comparison operators displaying the sum or difference l.jpg
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


Using comparison operators displaying the sum or difference continued l.jpg
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


Using comparison operators displaying the sum or difference continued23 l.jpg
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


Using comparison operators displaying the sum or difference continued24 l.jpg
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


Using comparison operators displaying the sum or difference continued25 l.jpg
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


Logical operators l.jpg
Logical Operators Difference (continued)

  • Logical operators:

    • Used to create compound conditions

    • Also called Boolean operators

  • Six logical operators in Visual Basic:

    • And

    • Or

    • Not

    • AndAlso

    • OrElse

    • Xor

Programming with Microsoft Visual Basic 2008, Fourth Edition


Logical operators continued l.jpg
Logical Operators (continued) Difference (continued)

Figure 4-18: Listing and examples of logical operators

Programming with Microsoft Visual Basic 2008, Fourth Edition


Logical operators continued28 l.jpg
Logical Operators (continued) Difference (continued)

  • 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 > 50000D Then…

    • If state is not TN, no need to evaluate sales > 50000D

Programming with Microsoft Visual Basic 2008, Fourth Edition


Logical operators continued29 l.jpg
Logical Operators (continued) Difference (continued)

Figure 4-19: Truth tables for the logical operators

Programming with Microsoft Visual Basic 2008, Fourth Edition


Logical operators continued30 l.jpg
Logical Operators (continued) Difference (continued)

Figure 4-19: Truth tables for the logical operators (continued)

Programming with Microsoft Visual Basic 2008, Fourth Edition


Logical operators continued31 l.jpg
Logical Operators (continued) Difference (continued)

Figure 4-19: Truth tables for the logical operators (continued)

Programming with Microsoft Visual Basic 2008, Fourth Edition


Using the truth tables l.jpg
Using the Truth Tables Difference (continued)

  • 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:

    • Evaluated after any arithmetic or comparison operators in the expression

Programming with Microsoft Visual Basic 2008, Fourth Edition


Using logical operators calculating gross pay l.jpg
Using Logical Operators: Calculating Gross Pay Difference (continued)

  • 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 AndAlso or OrElse

Programming with Microsoft Visual Basic 2008, Fourth Edition


Comparing strings containing letters l.jpg
Comparing Strings Containing Letters Difference (continued)

  • 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

Programming with Microsoft Visual Basic 2008, Fourth Edition


Comparing strings containing letters continued l.jpg
Comparing Strings Containing Letters (continued) Difference (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


Comparing strings containing letters continued36 l.jpg
Comparing Strings Containing Letters (continued) Difference (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


Converting a string to uppercase or lowercase l.jpg
Converting a String Difference (continued)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 strLetter.ToUpper = “p" Then

    • Note that strLetter’s value is not permanently converted

Programming with Microsoft Visual Basic 2008, Fourth Edition


Converting a string to uppercase or lowercase continued l.jpg
Converting a String to Uppercase or Lowercase (continued) Difference (continued)

Figure 4-24: Syntax and examples of the ToUpper and ToLower methods

Programming with Microsoft Visual Basic 2008, Fourth Edition


Converting a string to uppercase or lowercase continued39 l.jpg
Converting a String to Uppercase or Lowercase (continued) Difference (continued)

Figure 4-24: Syntax and examples of the ToUpper and ToLower methods (continued)

Programming with Microsoft Visual Basic 2008, Fourth Edition


Using the toupper and tolower methods displaying a message l.jpg
Using the ToUpper and ToLower Methods: Displaying a Message Difference (continued)

  • 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 textbox’s value converted to upper case

    Dim strState As String

    strState = txtState.Text.ToUpper

  • Use If/Else to test value and display message

Programming with Microsoft Visual Basic 2008, Fourth Edition


Comparing boolean values l.jpg
Comparing Boolean Values Difference (continued)

  • 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:

      If blnIsInsured = True Then

      or

      If blnIsInsured Then

  • Use Not logical operator to test for False value

Programming with Microsoft Visual Basic 2008, Fourth Edition


Comparing boolean values continued l.jpg
Comparing Boolean Values (continued) Difference (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


Comparing boolean values determining whether a string can be converted to a number l.jpg
Comparing Boolean Values: Determining Whether a String Can Be Converted to a Number

  • 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

Programming with Microsoft Visual Basic 2008, Fourth Edition


Comparing boolean values determining whether a string can be converted to a number continued l.jpg
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 TryParse method

Programming with Microsoft Visual Basic 2008, Fourth Edition


Lesson a summary l.jpg
Lesson A Summary be Converted to a Number (continued)

  • 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


Lesson a summary continued l.jpg
Lesson A Summary (continued) be Converted to a Number (continued)

  • Use text box’s CharacterCasing property to change text to upper or lower case

  • 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

Programming with Microsoft Visual Basic 2008, Fourth Edition


Lesson b objectives l.jpg
Lesson B Objectives be Converted to a Number (continued)

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

Programming with Microsoft Visual Basic 2008, Fourth Edition


Creating the monthly payment calculator application l.jpg
Creating the Monthly Payment Calculator Application be Converted to a Number (continued)

  • 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


Adding a group box to the form l.jpg
Adding a Group Box to the Form be Converted to a Number (continued)

  • 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

Programming with Microsoft Visual Basic 2008, Fourth Edition


Coding the monthly payment calculator application l.jpg
Coding the Monthly Payment Calculator Application be Converted to a Number (continued)

  • 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

Programming with Microsoft Visual Basic 2008, Fourth Edition


Coding the monthly payment calculator application continued l.jpg
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


Coding the btncalc control s click event procedure l.jpg
Coding the btnCalc Control’s (continued)Click Event Procedure

  • Tasks for btnCalc button’s Click event procedure:

    • Calculate monthly payment amount

    • Display result in lblPayment 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


Coding the btncalc control s click event procedure continued l.jpg
Coding the btnCalc Control’s (continued)Click Event Procedure (continued)

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

Programming with Microsoft Visual Basic 2008, Fourth Edition


Coding the btncalc control s click event procedure continued54 l.jpg
Coding the btnCalc Control’s (continued)Click Event Procedure (continued)

Figure 4-35: Partially completed Click event procedure

Programming with Microsoft Visual Basic 2008, Fourth Edition


Using the financial pmt method l.jpg
Using the Financial.Pmt Method (continued)

  • 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


Using the financial pmt method continued l.jpg
Using the Financial.Pmt Method (continued) (continued)

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

Programming with Microsoft Visual Basic 2008, Fourth Edition


Using the financial pmt method continued57 l.jpg
Using the Financial.Pmt Method (continued) (continued)

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

Programming with Microsoft Visual Basic 2008, Fourth Edition


The messagebox show method l.jpg
The MessageBox.Show Method (continued)

  • 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

Programming with Microsoft Visual Basic 2008, Fourth Edition


The messagebox show method continued l.jpg
The MessageBox.Show Method (continued) (continued)

Figure 4-41: Values returned by the MessageBox.Show method

Programming with Microsoft Visual Basic 2008, Fourth Edition


The messagebox show method continued60 l.jpg
The MessageBox.Show Method (continued) (continued)

Figure 4-41: Values returned by the MessageBox.Show method (continued)

Programming with Microsoft Visual Basic 2008, Fourth Edition


Lesson b summary l.jpg
Lesson B Summary (continued)

  • Group box is container control that treats its contents as one unit

  • Use Financial.Pmt method to calculate loan or investment payments

  • MessageBox.Show method displays message box with text, one or more buttons, and icon

Programming with Microsoft Visual Basic 2008, Fourth Edition


Lesson c objectives l.jpg
Lesson C Objectives (continued)

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


Coding the keypress event procedures l.jpg
Coding the KeyPress Event Procedures (continued)

  • 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

Programming with Microsoft Visual Basic 2008, Fourth Edition


Coding the keypress event procedures continued l.jpg
Coding the KeyPress Event Procedures (continued) (continued)

Figure 4-47: Code template for the txtPrincipal’s KeyPress event procedure

Programming with Microsoft Visual Basic 2008, Fourth Edition


Coding the keypress event procedures continued65 l.jpg
Coding the KeyPress Event Procedures (continued) (continued)

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

Programming with Microsoft Visual Basic 2008, Fourth Edition


Coding the keypress event procedures continued66 l.jpg
Coding the KeyPress Event Procedures (continued) (continued)

Figure 4-49: Completed CancelKeys procedure

Programming with Microsoft Visual Basic 2008, Fourth Edition


Coding the enter event procedure l.jpg
Coding the Enter Event Procedure (continued)

  • 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

Programming with Microsoft Visual Basic 2008, Fourth Edition


Coding the enter event procedure continued l.jpg
Coding the Enter Event Procedure (continued) (continued)

Figure 4-50: Syntax and an example of the SelectAll method

Programming with Microsoft Visual Basic 2008, Fourth Edition


Lesson c summary l.jpg
Lesson C Summary (continued)

  • KeyPress event occurs when user presses key

  • Use KeyPress 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 SelectAll method to select all contents of text box

Programming with Microsoft Visual Basic 2008, Fourth Edition


ad