1 / 50

Chapter 4: The Selection Structure

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

lola
Download Presentation

Chapter 4: The Selection Structure

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. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


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

  2. 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 Programming with Microsoft Visual Basic 2005, Third Edition

  3. 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 Programming with Microsoft Visual Basic 2005, Third Edition

  4. 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 Programming with Microsoft Visual Basic 2005, Third Edition

  5. 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 Programming with Microsoft Visual Basic 2005, Third Edition

  6. Writing Pseudocode for If and If/Else Selection Structures Figure 4-4: Examples of the If and If/Else selection structures written in pseudocode Programming with Microsoft Visual Basic 2005, Third Edition

  7. 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 Programming with Microsoft Visual Basic 2005, Third Edition

  8. 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 2005, Third Edition

  9. Coding the If and If/Else Selection Structures • Syntax • If conditionThen statement block for true path [Else statement block for false path] End If • condition must be a Boolean expression • The Else clause is optional Programming with Microsoft Visual Basic 2005, Third Edition

  10. 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 Programming with Microsoft Visual Basic 2005, Third Edition

  11. Comparison Operators (continued) Figure 4-7: Listing and examples of commonly used comparison operators (continued) Programming with Microsoft Visual Basic 2005, Third Edition

  12. Comparison Operators (continued) Figure 4-7: Listing and examples of commonly used comparison operators Programming with Microsoft Visual Basic 2005, Third Edition

  13. Using Comparison Operators–Swapping Numeric Values • 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 Programming with Microsoft Visual Basic 2005, Third Edition

  14. Using Comparison Operator–Swapping Numeric Values (continued) Figure 4-11: The If selection structure shown in the xDisplayButton’s Click event procedure Programming with Microsoft Visual Basic 2005, Third Edition

  15. 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 Programming with Microsoft Visual Basic 2005, Third Edition

  16. 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 Programming with Microsoft Visual Basic 2005, Third Edition

  17. 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 Programming with Microsoft Visual Basic 2005, Third Edition

  18. Logical Operators (continued) Figure 4-18: Listing and examples of logical operators (partial) Programming with Microsoft Visual Basic 2005, Third Edition

  19. Logical Operators (continued) Figure 4-19: Truth tables for the logical operators (continued) Programming with Microsoft Visual Basic 2005, Third Edition

  20. Logical Operators (continued) Figure 4-19: Truth tables for the logical operators Programming with Microsoft Visual Basic 2005, Third Edition

  21. 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 Programming with Microsoft Visual Basic 2005, Third Edition

  22. Using Truth Tables (continued) Figure 4-20: Order of precedence for arithmetic, comparison, and logical operators Programming with Microsoft Visual Basic 2005, Third Edition

  23. 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 Programming with Microsoft Visual Basic 2005, Third Edition

  24. Using Logical Operators: Calculating Gross Pay (continued) Figure 4-22: AndAlso and OrElse logical operators in the If...Then...Else statement (continued) Programming with Microsoft Visual Basic 2005, Third Edition

  25. Using Logical Operators: Calculating Gross Pay (continued) Figure 4-22: AndAlso and OrElse logical operators in the If...Then...Else statement Programming with Microsoft Visual Basic 2005, Third Edition

  26. 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 Programming with Microsoft Visual Basic 2005, Third Edition

  27. 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 Programming with Microsoft Visual Basic 2005, Third Edition

  28. 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 Programming with Microsoft Visual Basic 2005, Third Edition

  29. 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 Programming with Microsoft Visual Basic 2005, Third Edition

  30. Comparing Boolean Values (continued) Figure 4-29: Syntax and examples of the String.IsNullOrEmpty method Programming with Microsoft Visual Basic 2005, Third Edition

  31. Comparing Boolean Values (continued) Figure 4-31: Syntax and an example of using the Boolean value returned by the TryParse method Programming with Microsoft Visual Basic 2005, Third Edition

  32. 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 Programming with Microsoft Visual Basic 2005, Third Edition

  33. The Monthly Payment Calculator ApplicationLesson 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 Programming with Microsoft Visual Basic 2005, Third Edition

  34. 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 Programming with Microsoft Visual Basic 2005, Third Edition

  35. Completing the User Interface (continued) Figure 4-34: Sketch of the Monthly Payment Calculator user interface Programming with Microsoft Visual Basic 2005, Third Edition

  36. 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 Programming with Microsoft Visual Basic 2005, Third Edition

  37. 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 Programming with Microsoft Visual Basic 2005, Third Edition

  38. 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 Programming with Microsoft Visual Basic 2005, Third Edition

  39. Coding the xCalcPayButton Click Event Procedure (continued) Figure 4-39: Pseudocode for the xCalcButton’s Click event procedure Programming with Microsoft Visual Basic 2005, Third Edition

  40. 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 Programming with Microsoft Visual Basic 2005, Third Edition

  41. 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 Programming with Microsoft Visual Basic 2005, Third Edition

  42. The MessageBox.Show Method (continued) Figure 4-48: Completed xCalcButton’s Click event procedure Programming with Microsoft Visual Basic 2005, Third Edition

  43. The MessageBox.Show Method (continued) Figure 4-50: Message box created by the MessageBox.Show method Programming with Microsoft Visual Basic 2005, Third Edition

  44. 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 Programming with Microsoft Visual Basic 2005, Third Edition

  45. Completing the Monthly Payment Calculator ApplicationLesson C Objectives • Specify the keys that a text box will accept • Select the existing text in a text box Programming with Microsoft Visual Basic 2005, Third Edition

  46. 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 Programming with Microsoft Visual Basic 2005, Third Edition

  47. Coding the KeyPress Event Procedures (continued) Figure 4-54: Completed CancelKeys procedure Programming with Microsoft Visual Basic 2005, Third Edition

  48. 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 Programming with Microsoft Visual Basic 2005, Third Edition

  49. Coding the Enter Event Procedure (continued) Figure 4-57: Existing text selected in the xPrincipalTextBox Programming with Microsoft Visual Basic 2005, Third Edition

  50. 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 Programming with Microsoft Visual Basic 2005, Third Edition

More Related