programming with microsoft visual basic 2008 fourth edition chapter four the selection structure

Download Programming with Microsoft Visual Basic 2008 Fourth Edition Chapter Four The Selection Structure

If you can't read please download the document

Upload: shawn-golden

Post on 17-Jan-2018

220 views

Category:

Documents


0 download

DESCRIPTION

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

TRANSCRIPT

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 Programming with Microsoft Visual Basic 2008, Fourth Edition2 Figure 4-2: Monthly payment amount shown in the interface 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 applications 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 3 The Selection Structure Selection structure: Chooses one of two program flow paths based on a condition (maybe a composite 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 Edition4 The Selection Structure (continued) Programming with Microsoft Visual Basic 2008, Fourth Edition5 Figure 4-3: Selection structures you might use in daily life 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 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 Edition6 Writing Pseudocode (for If and If/Else Selection Structures) Programming with Microsoft Visual Basic 2008, Fourth Edition7 Figure 4-4: Examples of the If and If/Else selection structures written in pseudocode Flowcharting the If and If/Else Selection Structures Flowchart: Uses standardized symbols showing steps to be taken to accomplish a task Oval: Start/stop symbol Rectangle: Process symbol Parallelogram: symbol for I/O processing Diamond: Decision symbol Used in both selection and repetition structures Programming with Microsoft Visual Basic 2008, Fourth Edition8 Coding the If and If/Else Selection Structures IfThen and IfThenElse statements Used to 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 Edition9 10 Figure 4-5: Examples of the If and If/Else selection structures drawn in flowchart form Flowcharting (The If and If/Else Selection Structures) Comparison Operators 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 Edition11 Comparison Operators (continued) Programming with Microsoft Visual Basic 2008, Fourth Edition12 Figure 4-8: Evaluation steps for an expression containing arithmetic and comparison operators Logical Operators 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 Edition13 Precedence of Logical Operators Programming with Microsoft Visual Basic 2008, Fourth Edition14 Figure 4-18: Listing and examples of logical operators Logical Operators (continued) Short circuit evaluation: Bypasses evaluation of a condition when outcome can be determined without it Operators using technique: AndAlso, OrElse Example of short-circuit evaluation: 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 Edition15 Programming with Microsoft Visual Basic 2008, Fourth Edition16 Figure 4-19: Truth tables for the logical operators (continued) Logical Operators (continued) Programming with Microsoft Visual Basic 2008, Fourth Edition17 Figure 4-19: Truth tables for the logical operators (continued) Comparing Strings Containing Letters Simple Example Scenario: Display Pass if P or p is entered in txtLetter control Display Fail if F or 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 Edition18 Comparing Strings Containing Letters (continued) Programming with Microsoft Visual Basic 2008, Fourth Edition19 Figure 4-23: Visual Basic code showing string comparisons in the If...Then...Else statements condition Converting a String to Uppercase or Lowercase String comparisons are case sensitive CharacterCasing property of textbox control: 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 strLetters value is not permanently converted Programming with Microsoft Visual Basic 2008, Fourth Edition20 Converting a String to Uppercase or Lowercase (continued) Programming with Microsoft Visual Basic 2008, Fourth Edition21 Figure 4-24: Syntax and examples of the ToUpper and ToLower methods Converting a String to Uppercase or Lowercase (continued) Programming with Microsoft Visual Basic 2008, Fourth Edition22 Figure 4-24: Syntax and examples of the ToUpper and ToLower methods (continued) Comparing Boolean Values Boolean variable: Contains either True or False When testing for a True value, it is not necessary to include the = True OK 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 Edition23 Comparing Boolean Values (continued) Programming with Microsoft Visual Basic 2008, Fourth Edition24 Figure 4-27: Examples of comparing Boolean values in an IfThenElse statements condition Determining Whether a String Can Be Converted to a Number booleanVariable=dataType.TryParse(string, variable) TryParse method results in a numeric value for the variable after converting the string, or 0 if it cannot be converted TryParse also returns a Boolean value for booleanVariable indicating success or failure of the conversion attempt Use Boolean value returned by TryParse method in an IfThenElse statement Programming with Microsoft Visual Basic 2008, Fourth Edition25 Comparing Boolean Values: Determining Whether a String Can be Converted to a Number (continued) Programming with Microsoft Visual Basic 2008, Fourth Edition26 Figure 4-28: Syntax and example of using the Boolean value returned by the TryParse method Lesson A Summary In an expression, arithmetic operators are evaluated first, then comparison operators, and finally logical operators If...Then...Else statement: A Selection structure with a true path and a false path Use comparison operators to compare two values Use logical operators to create a compound condition Programming with Microsoft Visual Basic 2008, Fourth Edition27 Lesson A Summary (continued) Use text boxs 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 a string was successfully converted to numeric value Programming with Microsoft Visual Basic 2008, Fourth Edition28 Lesson B Objectives 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 button clicked by end-user in a message box Programming with Microsoft Visual Basic 2008, Fourth Edition29 Creating the Monthly Payment Calculator Application 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 Edition30 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 Programming with Microsoft Visual Basic 2008, Fourth Edition31 Coding the Monthly Payment Calculator Application Procedures required according to TOE chart: Code for click event procedures of 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 buttons Click event procedure Programming with Microsoft Visual Basic 2008, Fourth Edition32 Coding the Monthly Payment Calculator Application (continued) Programming with Microsoft Visual Basic 2008, Fourth Edition33 Figure 4-33: TOE chart for the Monthly Payment Calculator application Coding the btnCalc Controls Click Event Procedure Tasks for btnCalc buttons 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 Programming with Microsoft Visual Basic 2008, Fourth Edition34 Coding the btnCalc Controls Click Event Procedure (continued) Programming with Microsoft Visual Basic 2008, Fourth Edition35 Figure 4-34: Pseudocode for the btnCalc controls Click event procedure Coding the btnCalc Controls Click Event Procedure (continued) Programming with Microsoft Visual Basic 2008, Fourth Edition36 Figure 4-35: Partially completed Click event procedure Using the Financial.Pmt Method Calculates periodic payment on loan or investment 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 Edition37 Programming with Microsoft Visual Basic 2008, Fourth Edition38 Figure 4-36: Basic syntax and examples of the Financial.Pmt method Using the Financial.Pmt Method Programming with Microsoft Visual Basic 2008, Fourth Edition39 Figure 4-37: Selection structures true path coded in the procedure The MessageBox.Show Method MessageBox.show method: Displays message box with text message, caption, button(s), and icon. Programming with Microsoft Visual Basic 2008, Fourth Edition40 icon button(s) text message caption The MessageBox.Show Method 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: Question or Exclamation : Indicates user must make a decision before continuing Information: Indicates informational message Stop: Indicates serious problem Programming with Microsoft Visual Basic 2008, Fourth Edition41 Return Value of The MessageBox.Show Method Programming with Microsoft Visual Basic 2008, Fourth Edition42 Figure 4-41: Values returned by the MessageBox.Show method How to Use Return Value of The MessageBox.Show Method Programming with Microsoft Visual Basic 2008, Fourth Edition43 Figure 4-41: Values returned by the MessageBox.Show method Lesson B Summary 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 Edition44 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 Programming with Microsoft Visual Basic 2008, Fourth Edition45 Coding the KeyPress Event Procedures KeyPress event: Occurs when key is pressed while control has focus Character corresponding to pressed key is sent to KeyPress events e parameter KeyPress event can be used to prevent users from entering inappropriate characters Use e parameters KeyChar property to determine pressed key Use Handled property to cancel key if needed Programming with Microsoft Visual Basic 2008, Fourth Edition46 Coding the KeyPress Event Procedures (continued) Programming with Microsoft Visual Basic 2008, Fourth Edition47 Figure 4-47: Code template for the txtPrincipals KeyPress event procedure Programming with Microsoft Visual Basic 2008, Fourth Edition48 Figure 4-48: Examples of using the KeyChar and Handled properties in the KeyPress event procedure Coding the KeyPress Event Procedures (continued) Programming with Microsoft Visual Basic 2008, Fourth Edition49 Figure 4-49: Completed CancelKeys procedure Coding the Enter Event Procedure 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 boxs Enter event procedure Programming with Microsoft Visual Basic 2008, Fourth Edition50 Coding the Enter Event Procedure (continued) Programming with Microsoft Visual Basic 2008, Fourth Edition51 Figure 4-50: Syntax and an example of the SelectAll method Lesson C Summary 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 Edition52 Chap04\Monthly Payment.exe Chap04\Payment Solution IF MessageBox Financial Pmt KeyPress event IF Enter event text box Programming with Microsoft Visual Basic 2008, Fourth Edition53