Download presentation
Presentation is loading. Please wait.
Published byBrooke Stevenson Modified over 9 years ago
1
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley DECISION (IN EVERYDAY LIFE) The Gaddis and Irvine slides have been modified and added to by Dr. David Scanlan, CSUS
2
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Enter Exit DECISION (IF-THEN-ELSE) IN EVERYDAY LIFE THEN ELSE IF-THEN-ELSE control structure First, enter control structure and test the condition. IF the condition is true THEN do something, ELSE do something else. Lastly, exit the control structure and continue on... Often these IF-THEN-ELSE statements are called just "IF" statements for short.
3
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Enter Exit DECISION (IF-THEN-ELSE) IN EVERYDAY LIFE THENELSE IF-THEN-ELSE control structure First, enter control structure and test the condition. IF the condition is true THEN do something, ELSE do something else. Lastly, exit the control structure and continue on... Often these IF-THEN-ELSE statements are called just "IF" statements for short.
4
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Enter Exit DECISION (IF-THEN-ELSE) IN EVERYDAY LIFE THENELSE IF-THEN-ELSE control structure First, enter control structure and test the condition. IF the condition is true THEN do something, ELSE do something else. Lastly, exit the control structure and continue on... Often these IF-THEN-ELSE statements are called just "IF" statements for short.
5
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley DECISION (NESTED IF-THEN-ELSE) IN EVERYDAY LIFE NESTED IF-THEN-ELSE control structure First, enter control structure and test the condition. IF the condition is true THEN do something, ELSE test another condition etc... Lastly, exit the control structure and continue on... Notice that once you do something, you quit testing conditions and immediately exit the control structure. Enter Exit THENELSE THEN ELSE This is called "Case" structure or logic
6
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley DECISION (NESTED IF-THEN-ELSE) IN EVERYDAY LIFE ELSE THEN Enter Exit Another way to diagram nested IF-THEN-ELSE control structures. In my opinion, this is the BEST way, because it is clearer and easier to draw. NESTED IF-THEN-ELSE control structure First, enter control structure and test the condition. IF the condition is true THEN do something, ELSE test another condition etc... Lastly, exit the control structure and continue on... Notice that once you do something, you quit testing conditions and immediately exit the control structure. This is called "Case" structure or logic
7
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley ELSE THEN Enter Exit Enter Exit THENELSE THEN ELSE DECISION (NESTED IF-THEN-ELSE) IN EVERYDAY LIFE The logic for these two diagrams is EXACTLY the same. The one on the right is a better choice because it is CLEARER and EASIER to draw. Use this one. This is called "Case" structure or logic
8
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley DECISION (CASE) IN EVERYDAY LIFE CASE control structure diagram comparison: CASE has exactly the same logic as nested IF-THEN-ELSE. In a effort to simplify IF-THEN-ELSE statements that are nested in programming code, a new programming statement was introduced called CASE, and the flowchart representation for it was created (Bottom-right). Enter Exit RedYellowGreen ELSE THEN Enter Exit For CASE, you may use either for this class.If you use this CASE flowchart representation, you must use the CASE statement in your code, not nested IF-THEN- ELSE programming statements. This is called "Case" structure or logic
9
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley APPENDEX (FLOWCHART SYMBOLS USED IN THIS COURSE) Terminal symbol - This symbol indicates the starting or stopping point in the logic. Every flowchart should begin and end with a terminal symbol. Input/Output symbol - This symbol represents an input or output process in an algorithm, such as reading input or writing output. Process symbol - Represents any single process in an algorithm, such as assigning a value or performing a calculation. The flow of control is sequential. Predefined process symbol - Represents a module in an algorithm; that is, a predefined process that has its own flowchart, and code. Decision symbol - Represent a decision in the logic involving the comparison of two values. Alternative paths are followed depending on whether the decision symbol is true or false. Terminal Input/Output Process Predefined Process Decision Preparation Preparation symbol - In this course, use it for initializing loops.
10
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Flowlines - Connects various symbols in a flowchart, and contain an arrowhead. Use arrowhead when needed for clarity. You are strongly encouraged to use the Instructor's flowcharting style. His style takes slightly more time but you will find it more readable in the long run, and worth the extra effort. Salvage's style is as bad as it gets. Event symbol - In this course we will use a red terminal symbol to represent an event. There is no symbol for an event in ANSI flowchart symbols, thus the instructor created one. A red terminal symbol is a good choice because an EVENT, such as a button click, triggers the processing of the code within an event subroutine. EVENT APPENDEX (FLOWCHART SYMBOLS USED IN THIS COURSE)
11
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 4- 11 STARTING OUT WITH Visual Basic 2008 FOURTH EDITION Tony Gaddis Haywood Community College Kip Irvine Florida International University
12
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter Making Decisions and Working With Strings 4
13
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 4- 13 Introduction This chapter covers the Visual Basic decision statements If…Then If…Then…Else If…Then…ElseIf Select Case It also discusses the use of Radio Buttons Message Boxes [Note: There is always an Else as you will see.]
14
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley The Decision Structure 4.1 The Decision Structure Allows a Program to Have More Than One Path of Execution
15
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 4- 15 Order of Statement Execution Decision statements allow for changing the execution of the code's order of execution. Example: If decHoursWorked > 40D Then 'Process pay with overtime Else 'Process pay without overtime End If HoursWorked > 40D is the condition tested. If…Then…Else statement If…Then…Else
16
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley OVERTIME CALCULATION LOGIC TF Take this path IF the condition is False Take this path IF the condition is True HoursWorked > 40D is the condition tested. If…Then…Else
17
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley The If…Then Statement 4.2 The If…Then Statement Causes Other Statements to Execute Only Under a Certain Condition
18
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 4- 18 If…Then Statement Syntax New keywords used above: If Then End If condition Then statement (more statements as needed) Else End If There is always an implied Else in an If…Then statement. If condition Then 'Statement/s Else 'No statements End If See flowchart on next slide Else NOT PRESENT If…Then
19
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 4- 19 If…Then Example restated: If the condition is True execute Statement/s Else do nothing. Condition Statement(s) If True True False If contition Then 'Statement/s Else 'The Else word is not necessary, but it is implied. 'No statements are executed here. End If No statements are executed If the condition is False. [Note: There is always an Else] Then Else Not present, but implied. If…Then
20
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 4- 20 Relational Operators Test Conditions Usually a condition is formed using a relational operator A relational operator determines if a specific relationship exists between two values >Greater than <Less than =Equal to <>Not equal to >=Greater than or equal to <=Less than or equal to
21
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 4- 21 Binary Operators Relational operators use two operands, for example: intLength > intWidth Is length greater than width? intSize <= 10 Is size less than or equal 10? Relational operators yield a True or False result
22
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 4- 22 If…Then Examples ‘Bonus awarded if sales greater than 50000 If decSales > 50000D Then blnGetsBonus = True End If ‘Bonus, 12% commission rate, and a day off ‘awarded if sales greater than 50000 If decSales > 50000D Then blnGetsBonus = True decCommissionRate = 0.12 intDaysOff = intDaysOff + 1 End If Boolean value: The condition is True or False If…Then
23
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 4- 23 If…Then Rules The If and the Then must be on the same line Only a remark may follow the Then The End If must be on a separate line Only a remark may follow the End If Tutorial 4-1 presents an application that uses the If…Then statement If…Then
24
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 4- 24 If…Then Programming Style The code between the If…Then and the End If is indented Visual Basic does not require this It is a convention among programmers to aid in the readability of programs By default, the Visual Basic editor will automatically do this indentation as you enter your program If…Then
25
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 4- 25 Relational Operators with Math Operators Either or both relational operator operands may be mathematical expressions Math operators are evaluated before relational operators x+y and a-b are evaluated first Each result is then compared using the > operator If x + y > a - b Then lblMessage.Text = "It is true!" End If If…Then
26
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 4- 26 Relational Operators With Function Calls Either or both relational operator operands may be function calls If CInt(txtInput.Text) < 100 Then lblMessage.Text = "It is true!" End If If…Then
27
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 4- 27 Boolean Variables as Flags A flag is a Boolean variable that signals when some condition exists in the program Since a Boolean variable is either True or False, it can be used as the condition of an If Since a Boolean variable already evaluates to True or False, an operator is not required If blnQuotaMet Then lblMessage.Text = "You have met your sales quota" End If If blnQuotaMet = True Then lblMessage.Text = "You have met your sales quota" End If This example is more readable. If…Then
28
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley The If…Then…Else Statement 4.3 The If...Then...Else Statement Executes One Group of Statements If the Condition Is True and Another Group of Statements If the Condition Is False
29
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 4- 29 If…Then vs. If…Then…Else The If…Then construct will execute or ignore a group of statements (do something or do nothing) The If…Then…Else construct will execute one group of statements or another group (do this or do that) Tutorial 4-2 contains an example of the If…Then…Else construct
30
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 4- 30 If…Then Example showing implied Else. Condition Statement(s) If True True False If decTemperature < 40D Then lblMesage.Text = “A little cold, isn’t it?” Else 'The Else word is not necessary, but it is implied. 'No statements are executed here. End If No statements are executed If the condition is False. [Note: There is always an Else] Then Else Not needed. If…Then
31
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 4- 31 If…Then…Else Example Condition Statement(s) If True True False Statement(s) If False If decTemperature < 40D Then lblMesage.Text = “A little cold, isn’t it?” Else lblMesage.Text = “Nice weather we’re having!” End If ThenElse If…Then…Else
32
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley The If…Then…ElseIf Statement 4.4 The If...Then…Elseif Statement Is Like a Chain of If...Then...Else Statements They Perform Their Tests, One After the Other, Until One of Them Is Found to Be True
33
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 4- 33 Two Mutually Exclusive Choices The If…Then…Else has two choices The condition will either be True or False So either the Then clause or Else clause will be executed These are two mutually exclusive choices If…Then…Else
34
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 4- 34 Multiple Possible Choices The If…Then…ElseIf statement allows for an entire series of possible choices In pseudo code: If it is very cold Then Wear a coat Elseif it is chilly Wear a light jacket Elseif it is windy Wear a windbreaker Elseif it is hot Wear no jacket Called "Case" Logic or Structure If…Then…Elseif
35
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 4- 35 In Visual Basic Syntax If condition 1 Then Statement(s) 1 Elseif condition 2 Then Statements(s) 2 Elseif condition 3 Then Statements 3 … End If Called "Case" Logic or Structure If…Then…Elseif
36
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 4- 36 In Flowchart Form C1C1 C2C2 C3C3 Statement(s) 1 True Statement(s) 2 True Statement(s) 3 True False Called "Case" Logic or Structure If…Then…Elseif
37
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 4- 37 Example of ElseIf Usage If sngAverage < 60 Then lblGrade.Text = "F" ElseIf sngAverage < 70 Then lblGrade.Text = "D" ElseIf sngAverage < 80 Then lblGrade.Text = "C" ElseIf sngAverage < 90 Then lblGrade.Text = "B" ElseIf sngAverage <= 100 Then lblGrade.Text = "A" End If Does the order of these conditions matter? What happens if we reverse the order? Called "Case" Logic or Structure If…Then…Elseif
38
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 4- 38 ORDER REVERSED If sngAverage <= 100 Then lblGrade.Text = "A" ElseIf sngAverage < 90 Then lblGrade.Text = "B" ElseIf sngAverage < 80 Then lblGrade.Text = "C" ElseIf sngAverage < 70 Then lblGrade.Text = "D" ElseIf sngAverage < 60 Then lblGrade.Text = "F" End If Does the order of these conditions matter? What happened when the order is reversed? Answer: Everyone gets an "A" Called "Case" Logic or Structure If…Then…Elseif
39
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 4- 39 The Same Code Without ElseIf If sngAverage < 60 Then lblGrade.Text = "F" End If If sngAverage < 70 Then lblGrade.Text = "D" End If If sngAverage < 80 Then lblGrade.Text = "C" End If If sngAverage < 90 Then lblGrade.Text = "B" End If If sngAverage <= 100 Then lblGrade.Text = "A" End If Does this code function correctly? What is assigned to lblGrade for a 65 average? 75? If…Then
40
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 4- 40 The (Optional) Trailing Else A sequence of ElseIf’s may end with a plain Else, called a trailing Else If none of the conditions are True, the trailing Else statement(s) will be executed If…Then…Elseif
41
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 4- 41 Use of a Trailing Else If sngAverage < 60 Then lblGrade.Text = "F" ElseIf sngAverage < 70 Then lblGrade.Text = "D" ElseIf sngAverage < 80 Then lblGrade.Text = "C" ElseIf sngAverage < 90 Then lblGrade.Text = "B" ElseIf sngAverage <= 100 Then lblGrade.Text = "A" Else lblGrade.Text = "Invalid Average Grade" End If If average is greater than 100, lblGrade is assigned the text “Invalid” Called "Case" Logic or Structure If…Then…Elseif
42
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Nested If Statements 4.5 A Nested If Statement Is an If Statement in the Conditionally Executed Code of Another If Statement
43
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 4- 43 If Statements Within If Statements If statements within If statements create a more complex decision structure called a Nested If
44
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 4- 44 Nested If Example If decSalary > 30000D Then If intYearsOnJob > 2 Then lblMessage.Text = “Applicant qualifies." Else lblMessage.Text = “Applicant does not qualify." End If Else If intYearsOnJob > 5 Then lblMessage.Text = “Applicant qualifies." Else lblMessage.Text = “Applicant does not qualify." End If Note how the convention of indentations emphasizes the structure of nested Ifs. A bank customer qualifies for a special loan if: Earns over 30000 & on the job more than 2 years Or been on the job more than 5 years Nested If
45
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 4- 45 Simplification of the code on the last slide. Note how the convention of indentations emphasizes the structure of nested Ifs. A bank customer qualifies for a special loan if: Earns over 30000 & on the job more than 2 years Or been on the job more than 5 years If (decSalary > 30000D and intYearsOnJob > 2) Or intYearsOnJob > 5 Then lblMessage.Text = “Applicant qualifies." Else lblMessage.Text = “Applicant does not qualify." End If Simplified Code from last slide
46
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 4- 46 Flowchart Version intYearsOnJob > 2 sngSalary > 30000 intYearsOnJob > 5 lblMessage.Text = “Applicant qualifies." lblMessage.Text = “Applicant does not qualify." lblMessage.Text = “Applicant qualifies." lblMessage.Text = “Applicant does not qualify." False True
47
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Logical Operators 4.6 Logical Operators Combine Two or More Relational Expressions Into a Single Expression
48
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 4- 48 Visual Basic Logical Operators Operator Effect AndBoth operands must be true for the overall expression to be true, otherwise it is false Or One or both operands must be true for the overall expression to be true, otherwise it is false Xor One operand (but not both) must be true for the overall expression to be true, otherwise it is false Not Reverses the logical value of an expression
49
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 4- 49 The And Operator The truth table for the And Operator Condition 1 Condition 2 Condition 1 And Condition 2 TrueFalseFalse FalseTrueFalse FalseFalseFalse TrueTrueTrue If intTemperature 12 Then lblMessage.Text = “Temperature is in the danger zone." End If AndAlso operator [below] works identically but does not test intMinutes > 12 if intTemperature < 20 is false If intTemperature 12 Then lblMessage.Text = “Temperature is in the danger zone." End If
50
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 4- 50 The Or Operator The truth table for the Or Operator Condition 1Condition 2Condition 1 Or Condition 2 TrueFalseTrue FalseTrueTrue FalseFalseFalse TrueTrueTrue If intTemperature 100 Then lblMessage.Text = “Temperature is in the danger zone." End If OrElse operator works identically but does not test intTemperature > 100 when intTemperature < 20 is True.
51
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 4- 51 The Xor Operator If decTotal > 1000D Xor decAverage > 120D Then lblMessage.Text = “You may try again." End If The truth table for the Xor Operator Condition 1Condition 2Condition 1 Or Condition 2 TrueFalseTrue FalseTrueTrue FalseFalseFalse TrueTrueFalse
52
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 4- 52 The Not Operator The truth table for the Not Operator Condition 1 Not Condition 1 TrueFalse FalseTrue If Not decTemperature > 100D Then lblMessage.Text = "You are below the maximum temperature." End If Example: if decTemperature has a value of 120D then decTemperature > 100D is True. But, with the Not present, the condition is evaluated as Not True. In other words, the entire condition is evaluated as False.
53
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 4- 53 Checking Numerical Ranges Checking for a value inside a range uses And Checking for a value outside a range uses Or If x >= 20 And x <= 40 Then lblMessage.Text = “Value is in the acceptable range." End If If x 40 Then lblMessage.Text = “Value is outside the acceptable range." End If
54
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 4- 54 Precedence of Logical Operators Logical operators have an order of precedence just as arithmetic operators do From highest to lowest precedence Not And Or Xor As with arithmetic operations, parentheses are often used to clarify order of operations In MIS 15, ALWAYS use parentheses.
55
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 4- 55 Precedence of Logical Operators For example, in the statement If x 100 Or z = 50 x 100 is evaluated first Or z = 50 is evaluated last If the Or condition is to be evaluated first parentheses must be used If x 100 Or z = 50)
56
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 4- 56 Math, Relational, & Logical Operators Evaluate the following if a=5, b=7, x=100, y=30 If x > a * 10 And y < b + 20 Evaluating the math operators leaves us with If x > 50 And y < 27 Evaluating the relational operators leaves If True And False Evaluating the logical operators leaves False Parentheses make order of operations clear If (x > (a * 10)) And (y < (b + 20))
57
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Comparing Numeric Variables and Constants Notes by Dr. Scanlan Slides 57 to 67
58
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Comparing Numeric Variables Comparing Numeric Variables and Constants 1. In an algebraic comparison, the first thing that happens is that the sign (- or +) is taken into account. 2.Next, the size of the number is taken into account. 3.EXAMPLES: This condition will be evaluated as true, because -5D is less than 5D. Dim decX as Decimal = -5D Dim decY as Decimal = 5D If (decX < decY) Then lblDisplay.Text = "The condition is true." Else lblDisplay.Text = "The condition is false." End If Dim decX as Decimal = -1D Dim decY as Decimal = -5D If (decX < decY) Then lblDisplay.Text = "The condition is true." Else lblDisplay.Text = "The condition is false." End If Note: Constant comparisons are evaluated the same way as variables. This condition will be evaluated as false, because -1D is NOT less than -5D.
59
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Comparing Strings Notes by Dr. Scanlan Slides 57 to 67
60
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Comparing String Variables Comparing Strings 1. Generally, strings are compared using the same process you use when you are: (1) finding a word in a dictionary or, (2) finding a name in a telephone book. 2.We start the comparison using the left-most character and proceed, a character at a time, until we run out of characters for any of the two strings being compared, or until two characters being compared differ in value. Dim strName1 as String = "SCANLAN" Dim strName2 as String = "SCANLIN" If (strName1 < strName2) Then lblDisplay.Text = "The condition is true." Else lblDisplay.Text = "The condition is false." End If Which of these will come first in the telephone book? Why? We start with the "S" in both words and work our way thru. All the letters have an equal value until we compare "A" to "I". The earlier the capital letter appears in the alphabet, the lower its value in a string comparison. Since "A" is less than "I" we stop the comparison and declare the condition "True." See the next slides for the COMPLETE STORY on string comparisons.
61
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley ASCII collating sequence Every character used in computer systems has a number associated with it. These numbers are collectively call a "collating" sequence. When string values are compared, the comparison is made according to their collating sequence number. For example, on the previous slide the "I" has a value of 73 and the "A" has a value of 65. Thus, the "A" is less than the "I". Note that a lower case "i" has a value of 105 and the upper case "I" has a value of 73. Thus the upper case "I" is evaluated as less than the lower case "i". The ASCII sequence on the right is a subset of Unicode which has 65,536 characters in it. Visual Basic.NET uses Unicode which uses 16 bits for each character stored. These character above represent only a few of Unicode's 65,536 characters.
62
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley ASCII (subset of Unicode) collating sequence You must know the following order in the collating sequence: Blank (space) Numbers Capital letters Lower case letters These characters above represent some of the 128 characters in ASCII. Decimal values Decimal values Decimal values
63
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley How Characters in a String are Stored in Memory
64
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley ASCII (subset of Unicode) collating sequence These binary values on the left are stored in memory and represent characters. Unicode in binary: Blank: (32 in decimal) 0000000000100000 0: (48 in decimal) 0000000000110000 A: (65 in decimal) 0000000001000001 a: (97 in decimal) 0000000001100001 ASCII and Unicode ASCII is an old standard and only represents 128 characters. ASCII code uses 7 bits. Unicode is a new standard and represents 65,536 different characters using 16 bits. ASCII code is incorporated into Unicode and uses the first 7 bits of Unicode. Visual Basic.NET uses Unicode to store each character in a string; thus, 16 bits (2 bytes) are used to store every character stored as "char" or string" data types. 16 bits: Count them. MEMORY
65
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Converting Binary to Decimal the Easy Way Unicode in binary: Blank: (32 in decimal) 0000000000100000 0: (48 in decimal) 0000000000110000 A: (65 in decimal) 0000000001000001 a: (97 in decimal) 0000000001100001... 512 256 128 64 32 16 8 4 2 1 a = a = 97 = 64 + 32 + 1 Unicode ASCII
66
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley How Characters in a String are "Really" Compared Notes by Dr. Scanlan Slides 57 to 67
67
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley ASCII (subset of Unicode) collating sequence When comparing a capital "A" with a lowercase "a" this is what is happening within the machine: Unicode binary values are compared within the Logic part of the microprocessor's ALU (Arithmetic-Logic Unit). If 0000000001000001 < 0000000001100001 Then lblDisplay.Text = "Uppercase A" Else lblDisplay.Text = "Lowercase a" End If A a If "A" < "a" Than lblDisplay.Text = "Capital A" Then Else lblDisplay.Text = "Lowercase a" End If (65) (97)
68
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Comparing, Testing, and Working With Strings 4.7 This Section Shows You How to Use Relational Operators to Compare Strings, and Discusses Several Intrinsic Functions That Perform Tests and Manipulations on Strings
69
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 4- 69 Strings Can Be Compared strName1 = "Mary" strName2 = "Mark" If strName1 = strName2 Then lblMessage.Text = “Names are the same" Else lblMessage.Text = “Names are NOT the same" End If If strMonth <> "October" Then ' statement End If Relational operators can be used to compare strings and string literals as well as numbers
70
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 4- 70 How Are Strings Compared? Each character is encoded as a numerical value using the Unicode standard Letters are arranged in alphabetic order The Unicode numeric code for A is less than the Unicode numeric code for B Characters of each string are compared one by one until a difference is found M a r y M a r k Mary is greater than Mark because “ y ” has a Unicode value greater than “ k ”
71
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 4- 71 How Are Strings Compared? Upper case letters do not have the same value as their lower case equivalents Upper case letters are less than lower case The >, =, and <= operators can be used with strings as well If one string is shorter than another, spaces are substituted for the missing characters Spaces have a lower value than letters “Hi” has 2 spaces added if compared to “High” “Hi ” is less than “High”
72
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 4- 72 The Empty String A space (or blank) is considered a character An empty string is a string with no characters A string with just spaces has characters in it The empty string is written as "", as in the following code that tests for no input: If txtInput.Text = "" Then lblMessage.Text = "Please enter a value" End If
73
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 4- 73 ToUpper Method ToUpper method can be applied to a string Results in a string with lowercase letters converted to uppercase The original string is not changed littleWord = "Hello" bigWord = littleWord.ToUpper() ' littleWord retains the value "Hello" ' bigWord is assigned the value "HELLO"
74
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 4- 74 ToLower Method The ToLower method performs a similar but opposite purpose Can be applied to a string Results in a string with the lowercase letters converted to uppercase The original string is not changed bigTown = “New York" littleTown = bigTown.ToLower() ' bigTown retains the value “New York" ' littleTown is assigned the value “new york"
75
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 4- 75 A Handy Use for ToUpper or ToLower ToUpper or ToLower can be used to perform case insensitive comparisons of strings 1st comparison below is false “Hello”<>“hello” 2nd comparison is true ToLower converts both strings to lower case Causes “hello” to be compared to “hello” Tutorial 4-6 demonstrates how this is used word1 = "Hello“ Word2 = “hello” If word1 = word2 ‘false, not equal If word1.ToLower() = word2.ToLower() ‘true, equal
76
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 4- 76 IsNumeric Function This function accepts a string as an argument and returns True if the string contains a number Dim strNumber as String strNumber = “576” If IsNumeric(strNumber)‘returns true strNumber = “123abc” If IsNumeric(strNumber)‘returns false Use IsNumeric function to determine if a given string contains numeric data
77
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 4- 77 Determining the Length of a String The Length method determines the length of a string, e.g.: If txtInput.Text.Length > 20 Then lblMessage.Text = “Enter fewer than 20 characters." End If Note: txtInput.Text.Length means to apply the Length Method to the value of the Text property of the Object txtInput
78
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 4- 78 Trimming Spaces from Strings There are three Methods that remove spaces from strings: TrimStart – removes leading spaces TrimEnd – removes trailing spaces Trim – removes leading and trailing spaces greeting = " Hello " lblMessage1.Text = greeting.TrimStart() ' Returns the value "Hello " lblMessage1.Text = greeting.Trim() ‘ Returns the value "Hello"
79
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 4- 79 The Substring Method The Substring method returns a portion of a string or a “string within a string” (a substring) Each character position is numbered sequentially with the 1 st character referred to as position zero StringExpression.Substring(Start) returns the characters from the Start position to the end StringExpression.Substring(Start, Length) returns the number of characters specified by Length beginning with the Start position
80
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 4- 80 Substring Method Examples Dim firstName As String Dim fullName As String = "George Washington" firstName = fullName.Substring(0, 6) ' firstName assigned the value "George" ' fullName is unchanged lastName = fullName.Substring(7) ‘ lastName assigned the value “Washington” ‘ fullName unchanged Position 0Position 7
81
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 4- 81 Search for a String Within a String Use the IndexOf method StringExpression.IndexOf(Searchstring) Searches the entire string for Searchstring StringExpression.IndexOf(SearchString, Start) Starts at the character position Start and searches for Searchstring from that point StringExpr.IndexOf(SearchString, Start, Count) Starts at the character position Start and searches Count characters for SearchString
82
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley IndexOf will return the starting position of the SearchString in the string being searched Positions are numbered from 0 (for the first) If SearchString is not found, a -1 is returned Tutorial 4-7 provides an opportunity to work with several of the string methods Dim name As String = "Angelina Adams" Dim position As Integer position = name.IndexOf("A", 1) ' position has the value 9 Position 0 Position 9 Slide 4- 82 IndexOf Method Examples
83
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley The Message Box 4.8 Sometimes You Need a Convenient Way to Display a Message to the User This Section Discusses the Messagebox.Show Method, Which Allows You to Display a Message in a Dialog Box
84
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 4- 84 Message Box Arguments A message box is a dialog box with a user message in a pop-up window The following can be specified Message - text to display within the box Caption - title for the top bar of the box Buttons - indicates which buttons to display Icon - indicates icon to display DefaultButton - indicates which button corresponds to the Return Key All arguments but the Message are optional Use of an argument requires those before it
85
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 4- 85 MessageBox Buttons Argument MessageBoxButtons.AbortRetryIgnore Displays Abort, Retry, and Ignore buttons MessageBoxButtons.OK Displays only an OK button MessageBoxButtons.OKCancel Displays OK and Cancel buttons MessageBoxButtons.RetryCancel Display Retry and Cancel buttons MessageBoxButtons.YesNo Displays Yes and No buttons MessageBoxButtons.YesNoCancel Displays Yes, No, and Cancel buttons
86
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley MessageBox Icon Argument Slide 4- 86 The Icon argument specifies a particular type of icon to appear in the message box There are 4 possible icons shown to the left Note that some values show the same icon
87
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 4- 87 Example Message Box MessageBox.Show("Do you wish to continue?", _ "Please Confirm", _ MessageBoxButtons.YesNo, _ MessageBoxIcon.Question)
88
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 4- 88 Which Button Was Clicked MessageBox returns a value indicating which button the user clicked: DialogResult.Abort DialogResult.Cancel DialogResult.Ignore DialogResult.No DialogResult.OK DialogResult.Retry DialogResult.Yes
89
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 4- 89 Which Button Was Clicked Example Dim result As Integer result = MessageBox.Show("Do you wish to continue?", _ "Please Confirm", MessageBoxButtons.YesNo) If result = DialogResult.Yes Then ' Perform an action here ElseIf result = DialogResult.No Then ' Perform another action here End If
90
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley The Select Case Statement 4.9 In a Select Case Statement, One of Several Possible Actions Is Taken, Depending on the Value of an Expression
91
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 4- 91 Select Case Statement Similar to If…Then…ElseIf Performs a series of tests Conditionally executes the first true condition Select Case is different in that: A single test expression may be evaluated The test expression is listed once The possible values of the expression are then listed with their conditional statements Case Else may be included and executed if none of the values match the expression
92
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 4- 92 Find Day of Week With Select Case Select Case CInt(txtInput.Text) Case 1 MessageBox.Show("Day 1 is Monday.") Case 2 MessageBox.Show("Day 2 is Tuesday.") Case 3 MessageBox.Show("Day 3 is Wednesday.") Case 4 MessageBox.Show("Day 4 is Thursday.") Case 5 MessageBox.Show("Day 5 is Friday.") Case 6 MessageBox.Show("Day 6 is Saturday.") Case 7 MessageBox.Show("Day 7 is Sunday.") Case Else MessageBox.Show("That value is invalid.") End Select
93
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 4- 93 Select Case With Multiple Values Select Case strAnimal Case "Dogs", "Cats" MessageBox.Show ("House Pets") Case "Cows", "Pigs", "Goats" MessageBox.Show ("Farm Animals") Case "Lions", "Tigers", "Bears" MessageBox.Show ("Oh My!") End Select
94
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 4- 94 Select Case with Operators Select Case intScore Case Is >= 90 strGrade = “A” Case 80 to 89 strGrade = “B” Case 70 to 79 strGrade = “C” Case 60 to 69 strGrade = “D” Case 0 to 59 strGrade = “F” Case Else MessageBox.Show(“Invalid Score”) End Select Tutorial 4-8 demonstrates the Select Case
95
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Introduction to Input Validation 4.10 Input Validation Is the Process of Inspecting Input Values and Determining Whether They Are Valid
96
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 4- 96 Validation Example Output is only as good as the input “Garbage In, Garbage Out”…GIGO Input validation is the process of inspecting user input to see that it meets certain rules The TryParse method verifies that an input value is in a valid numeric or date format Decision structures are often used to validate input
97
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 4- 97 The TryParse Method Converts an input value to another format Verifies input format of entered data Returns Boolean value True if successful False if unsuccessful Types of data useable with TryParse method: All numeric variables Date and Boolean data types
98
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 4- 98 Example: TryParse method with an integer value Dim intResult As Integer If Integer.TryParse(txtInput.Text, intResult) Then lblMessage.Text = "Success!" intTotal = intResult + 150 Else lblMessage.Text = "Error: an integer was not found" End If Tests the Text property to see if the text value can be cast into an integer. If the cast is successful, the integer value is placed into intResult for use in the program somewhere.
99
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 4- 99 Verify Date Entry With TryParse Dim datBirth As Date If Not Date.TryParse(txtInput.Text, datBirth) Then lblMessage.Text = “Not a valid date!“ End If Tests the Text property to see if the text value can be cast into a date. If the cast is successful, the date value is placed into datBirth for use in the program somewhere.
100
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 4- 100 TRY/CATCH Will do all that TryParse will do. Dr. Scanlan prefers TryCatch Types of validations TryCatch will check: CInt() CBool() CStr() CByte() CChar() CDec() CDbl() CSng() Clng() CShort() CDate()
101
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 4- 101 Using If To Check Range of Values ' Validate the input to ensure that ' no negative numbers were entered. If decSales < 0 Or decAdvance < 0 Then MessageBox.Show("Please enter positive numbers" & _ " for sales and/or advance pay.“, “Error”) End If Decision structures often used to validate input Example verifies that entries for both decSales and decAdvance are positive numbers
102
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Radio Buttons and Check Boxes 4.11 Radio Buttons Appear in Groups of Two or More and Allow the User to Select One of Several Possible Options Check Boxes Allow an Item to Be Selected or Deselected by Checking or Unchecking a Box
103
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 4- 103 Radio Buttons
104
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 4- 104 Radio Buttons Used when only one of several possible options may be selected at one time Car radio buttons select one station at a time May be placed in a group box Group box defines a set of radio buttons Can select only one button within a group box Those on a form but not inside a group box are considered members of the same group Radio buttons have a boolean Checked property and a CheckChanged event
105
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 4- 105 Checking Radio Buttons in Code If radCoffee.Checked = True Then MessageBox.Show("You selected Coffee") ElseIf radTea.Checked = True Then MessageBox.Show("You selected Tea") ElseIf radSoftDrink.Checked = True Then MessageBox.Show("You selected a Soft Drink") End If
106
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 4- 106 CheckBoxes
107
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 4- 107 Check Boxes Can select: One or more checkboxes at a time. Check boxes: Checked property CheckChanged event Tutorial 4-9 provides radio button and check box examples
108
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Check Property (True or False) If CheckBox4.Checked = True Then MessageBox.Show("You selected Choice 4") End If The Checked Property is tested for True or False
109
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 4- 109 Checked Event Private Sub CheckBox4_CheckedChanged(ByVal sender As Object, _ ByVal e As System.EventArgs) Handles CheckBox4.CheckedChanged MessageBox.Show ("CheckBox4 was checked or unchecked") End Sub This is a CheckedChanged Event. It is triggered when CheckBox4 is checked or unchecked.
110
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 4- 110 Checking Check Boxes in Code Private Sub CheckBox4_CheckedChanged(ByVal sender As Object, _ ByVal e As System.EventArgs) Handles CheckBox4.CheckedChanged If CheckBox4.Checked = True Then MessageBox.Show("Hello") End If If CheckBox4.Checked = False Then MessageBox.Show("Goodbye") End If End Sub When CheckBox4 is checked, the Message is Hello. When CheckBox4 is unchecked, the Message is Goodbye.
111
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Module-level variables are the same as Class-level variables 4.12 Module-level variables are not local to any procedure. In a Form, they are declared outside of any procedure, and may be accessed by statements in any procedure in the same Form Covered in Chapter 3 notes, also.
112
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 4- 112 Scope of Module-level variables Variable scope refers to the portion of a program in which that variable is visible or usable. Variables declared inside a procedure or method have local-level scope Only visible inside that procedure or method Sometimes a variable needs to be visible to many procedures or methods within a form Variables declared outside a procedure but within a form have module-level scope These are visible throughout the form Makes communication between procedures easy
113
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Declaring a Module-Level Variable Public Class Form1 Dim mdecTotalSalary As Decimal‘Module-level variable Private Sub btnAddWeekly_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAddWeekly.Click Dim decWeeklyPay As Decimal'Local variable decWeeklyPay = CDec(txtPay.Text) mdecTotalSalary += decWeeklyPay End Sub Slide 4- 113 Module-level variables are declared in the Declaration Section Local-level variables are declared within a procedure. Declaration Section
114
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 4- 114 Module-level Variables Disadvantages Module-level variables should be used sparingly - only when really needed. Why? Increases COUPLING BETWEEN PROCEDURES.
115
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley The Health Club Membership Fee Calculator Application 4.13 The Health Club Membership Fee Calculator uses features discussed in this chapter, including If statements, a Select Case statement, radio buttons, and check boxes
116
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Health Club Fee Calculator Form Slide 4- 116
117
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Calculate Button Click Event Flowchart Slide 4- 117
118
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Base Monthly Fee Calculation Flowchart Slide 4- 118 Uses a series of ElseIf statements
119
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Calculate Optional Services Flowchart Slide 4- 119 Uses several If...Then statements
120
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Compute Discount Flowchart Slide 4- 120 Uses a Select Case statement
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.