Download presentation
Presentation is loading. Please wait.
Published byCarmella Harvey Modified over 9 years ago
1
Starting Out with Visual Basic.NET 2 nd Edition Chapter 4 Making Decisions and Working With Strings
2
Starting Out with Visual Basic.NET 2 nd Edition 4.1 Introduction
3
Starting Out with Visual Basic.NET 2 nd Edition Chapter 4 Topics This chapter covers the Visual Basic.NET decision statements If … Then ElseIf It also discusses the use of Radio Buttons Message Boxes Comparisons and Strings
4
Starting Out with Visual Basic.NET 2 nd Edition 4.2 The Decision Structure The Decision Structure Allows a Program to Have More Than One Path of Execution
5
Starting Out with Visual Basic.NET 2 nd Edition Order of Statement Execution Thus far, all of our code statements have been executed sequentially To write meaningful programs our code needs to be able to Execute code conditionally (this chapter) Repeat sections of code (next chapter)
6
Starting Out with Visual Basic.NET 2 nd Edition The Decision Structure Flowchart of a typical decision structure Evaluate the condition Execute, or not some code Condition Conditional Code True False
7
Starting Out with Visual Basic.NET 2 nd Edition 4.3 The If…Then Statement The If…Then Statement Causes Other Statements to Execute Only Under a Certain Condition
8
Starting Out with Visual Basic.NET 2 nd Edition If…Then Statement Syntax New keywords used above: If Then End If condition Then statement (more statements as needed) End If
9
Starting Out with Visual Basic.NET 2 nd Edition Relational Operators Usually the condition is formed with a relational operator >Greater than <Less than =Equal to <>Not equal to >=Greater than or equal to <=Less than or equal to
10
Starting Out with Visual Basic.NET 2 nd Edition Binary Relational Operators Operators are classified as to how many operands each takes Relational operators are binary operators -- each has two operands, e.g. length > width size <= 10 Relational operators yield a True or False (Boolean) result
11
Starting Out with Visual Basic.NET 2 nd Edition If…Then Examples If sales > 50000 Then getsBonus = True End If If sales > 50000 Then getsBonus = True commissionRate = 0.12 daysOff = daysOff + 1 End If
12
Starting Out with Visual Basic.NET 2 nd Edition 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'
13
Starting Out with Visual Basic.NET 2 nd Edition If…Then Conventions The code between the 'If…Then' and the 'End If' is indented Visual Basic.NET does not require this It is a convention among programmers to aid in the readability of programs By default, the Visual Basic.NET editor will automatically do this indentation as you enter your program
14
Starting Out with Visual Basic.NET 2 nd Edition Relational Operators with Math Operators Either or both of the relational operator operands may themselves be expressions Math operators are done before the relational operators If x + y > a - b Then lblMessage.Text = "It is true!" End If
15
Starting Out with Visual Basic.NET 2 nd Edition Relational Operators with Function Calls Either or both of the relational operator operands may themselves be function calls If Val(txtInput.Text) < 100 Then lblMessage.Text = "It is true!" End If
16
Starting Out with Visual Basic.NET 2 nd Edition Boolean Variables as Flags A flag is a Boolean variable that signals when some condition exists in the program They can be used as the condition Dim quotaMet as Boolean quotaMet = sales >= quota If quotaMet Then lblMessage.Text = "You have met your sales quota" End If
17
Starting Out with Visual Basic.NET 2 nd Edition What an 'If…Then' Really Tests For Visual Basic.NET first evaluates the conditional expression If the result is 0, the condition is regarded as being False If the result is anything else, the condition is regarded as being True
18
Starting Out with Visual Basic.NET 2 nd Edition 4.4 The If…Then…Else Statement 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
19
Starting Out with Visual Basic.NET 2 nd Edition 'If…Then' vs. 'If…Then…Else' The 'If…Then' construct will execute or not 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)
20
Starting Out with Visual Basic.NET 2 nd Edition The 'If…Then…Else' Structure Condition Execute If True True False Execute If False
21
Starting Out with Visual Basic.NET 2 nd Edition 'If…Then…Else' Example If temperature < 40 Then lblMesage.Text = “A little cold, isn’t it?” Else lblMesage.Text = “Nice weather we’re having!” End If
22
Starting Out with Visual Basic.NET 2 nd Edition 4.5 The If…Then…ElseIf Statement 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
23
Starting Out with Visual Basic.NET 2 nd Edition Two Mutually Exclusive Choices ('If…Then…Else') The 'If…Then…Else' statement has two choices The conditional statement will either be True or False Hence, exactly one of the two choices will be selected They are mutually exclusive
24
Starting Out with Visual Basic.NET 2 nd Edition More Than Two Mutually Exclusive Choices The 'If…Then…ElseIf' statement provides a series of mutually exclusive 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 Elesif it is hot Wear no jacket
25
Starting Out with Visual Basic.NET 2 nd Edition In Visual Basic.NET Syntax If condition 1 Then Statement(s) 1 Elseif condition 2 Then Statements(s) 2 Elseif condition 3 Then Statements 3 … End If
26
Starting Out with Visual Basic.NET 2 nd Edition In Flowchart Form C1C1 C2C2 C3C3 Statement(s) 1 True Statement(s) 2 True Statement(s) 3 True False
27
Starting Out with Visual Basic.NET 2 nd Edition Example of Usage If average < 60 Then lblGrade.Text = "F" ElseIf average < 70 Then lblGrade.Text = "D" ElseIf average < 80 Then lblGrade.Text = "C" ElseIf average < 90 Then lblGrade.Text = "B" ElseIf average <= 100 Then lblGrade.Text = "A" End If
28
Starting Out with Visual Basic.NET 2 nd Edition Contrast the Preceding Code To This Code Without the Elses (This is less efficient because every condition is checked) If average < 60 Then lblGrade.Text = "F" End If If average < 70 Then lblGrade.Text = "D" End If If average < 80 Then lblGrade.Text = "C" End If If average < 90 Then lblGrade.Text = "B" End If If average <= 100 Then lblGrade.Text = "A" End If
29
Starting Out with Visual Basic.NET 2 nd Edition The (Optional) Trailing Else A sequence of ElseIfs may end with a plain else (called a trailing Else) If none of the conditions were True, the statement(s) after this Else will be executed Continuing with the preceding example on the next slide:
30
Starting Out with Visual Basic.NET 2 nd Edition Use of a Trailing Else If average < 60 Then lblGrade.Text = "F" ElseIf average < 70 Then lblGrade.Text = "D" ElseIf average < 80 Then lblGrade.Text = "C" ElseIf average < 90 Then lblGrade.Text = "B" ElseIf average <= 100 Then lblGrade.Text = "A" Else lblGrade.Text = "Invalid" End If
31
Starting Out with Visual Basic.NET 2 nd Edition 4.6 Nested If Statements A Nested If Statement Is an If Statement in the Conditionally Executed Code of Another If Statement
32
Starting Out with Visual Basic.NET 2 nd Edition 'If' Statements Within 'If' Statements Inside of any of the styles of 'If' statements that we have seen, the statement(s) portion can be any combination of statements This includes other 'If' statements Hence more complex decision structures can be created (by nesting 'Ifs' within 'Ifs')
33
Starting Out with Visual Basic.NET 2 nd Edition Consider This Code If Val(txtSalary.Text) > 30000 Then If Val(txtYearsOnJob.Text) > 2 Then lblMessage.Text = "The applicant qualifies." Else lblMessage.Text = "The applicant does not qualify." End If Else If Val(txtYearsOnJob.Text) > 5 Then lblMessage.Text = "The applicant qualifies." Else lblMessage.Text = "The applicant does not qualify." End If Note how the convention of indentations emphasizes the structure of nested Ifs.
34
Starting Out with Visual Basic.NET 2 nd Edition Flowchart Version Val(txtYearsOnJob.Text) > 5 Val(txtSalary.Text) > 30000 Val(txtYearsOnJob.Text) > 2 lblMessage.Text = "The applicant qualifies." lblMessage.Text = "The applicantdoes not qualify." lblMessage.Text = "The applicant qualifies." lblMessage.Text = "The applicantdoes not qualify." False True
35
Starting Out with Visual Basic.NET 2 nd Edition 4.7 Logical Operators Logical Operators Connect Two or More Relational Expressions Into One, or Reverse the Logic of an Expression
36
Starting Out with Visual Basic.NET 2 nd Edition Visual Basic.NET Logical Operators OperatorEffect 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
37
Starting Out with Visual Basic.NET 2 nd Edition The 'And' Operator Truth Table for 'And' Operator Expression 1 Expression 2 Expression 1 And Expression 2 TrueFalseFalse FalseTrueFalse FalseFalseFalse TrueTrueTrue If temperature 12 Then lblMessage.Text = "The temperature is in the danger zone." End If
38
Starting Out with Visual Basic.NET 2 nd Edition The 'Or' Operator Truth Table for 'Or' Operator Expression 1 Expression 2 Expression 1 Or Expression 2 TrueFalseTrue FalseTrueTrue FalseFalseFalse TrueTrueTrue If temperature 100 Then lblMessage.Text = "The temperature is in the danger zone." End If
39
Starting Out with Visual Basic.NET 2 nd Edition The 'Xor' Operator Truth Table for 'Xor' Operator Expression 1 Expression 2 Expression 1 Xor Expression 2 TrueFalseTrue FalseTrueTrue FalseFalseFalse TrueTrueFalse If total > 1000 Xor average > 120 Then lblMessage.Text = “You may try again." End If
40
Starting Out with Visual Basic.NET 2 nd Edition The 'Not' Operator Truth Table for 'Not' Operator Expression 1 Not Expression 1 TrueFalse FalseTrue If Not temperature > 100 Then lblMessage.Text = "You are below the maximum temperature." End If
41
Starting Out with Visual Basic.NET 2 nd Edition Checking Numerical Ranges Checking for a value inside of a range: Checking for a value outside of a range: If x >= 20 And x <= 40 Then lblMessage.Text = "The value is in the acceptable range." End If If x 40 Then lblMessage.Text = "The value is outside the acceptable range." End If
42
Starting Out with Visual Basic.NET 2 nd Edition Short-circuit Evaluation AndAlso – equivalent to And, except that if left side is False, right side not even evaluated (whole expression would be false) OrElse – equivalent to Or, except that if left side is True, right side not even evaluated (whole expression would be true)
43
Starting Out with Visual Basic.NET 2 nd Edition Relative Precedence of the Logical Operators From highest to lowest precedence Not (unary + and -) The binary arithmetic operators The relational operators And Or Xor
44
Starting Out with Visual Basic.NET 2 nd Edition Meaning of the Relative Precedence Ordering, I 'Not' and the other unary operators are done first if in the middle of an expression Then the normal mathematical operators are done Then the relational operators are done Then the logical operators are done in the order of 'And', 'Or', 'Xor'
45
Starting Out with Visual Basic.NET 2 nd Edition Meaning of the Relative Precedence Ordering, II For the most part, the operators will be done in the order that seems "logical" to the programmer It is likely, however, that one's program will need parentheses to force the needed ordering of the logical operators (when they appear in the same expression)
46
Starting Out with Visual Basic.NET 2 nd Edition 4.8 Comparing, Testing, and Working With Strings This Section Shows You How to Use Relational Operators to Compare Strings, and Discusses Several Intrinsic Functions That Perform Tests and Manipulations on Strings
47
Starting Out with Visual Basic.NET 2 nd Edition Strings Can Be Compared in the Same Way That Numbers Are Compared name1 = "Mary" name2 = "Mark" If name1 = name2 Then lblMessage.Text = "The names are the same" Else lblMessage.Text = "The names are NOT the same" End If If month <> "October" Then ' statement End If
48
Starting Out with Visual Basic.NET 2 nd Edition How Are Strings Compared? Each character is encoded as a numerical value using the Unicode standard The characters of each string are compared, pair by pair (first with first, second with second, etc.) until a difference is found The ordering is then the numerical ordering of the differing characters Unicode encoding is structured to provide alphabetical ordering
49
Starting Out with Visual Basic.NET 2 nd Edition The Empty String The empty string is a string with no characters in it (not even space characters) The empty string is written as "", as in: If txtInput.Text = "" Then lblMessage.Text = "Please enter a value" End If
50
Starting Out with Visual Basic.NET 2 nd Edition ToUpper Method The ToUpper method when applied to a string yields a string with the lowercase letters converted to uppercase The original string is not changed littleWord = "Hello" bigWord = littleWord.ToUpper ' littleWord maintains the value "Hello" ' bigWord is assigned the value "HELLO"
51
Starting Out with Visual Basic.NET 2 nd Edition ToLower Method The ToLower method works correspondingly -- converting any uppercase letters in a string to lowercase
52
Starting Out with Visual Basic.NET 2 nd Edition A Handy Use for ToUpper or ToLower The character 'A' has a different Unicode value from the letter 'a' So if one's program needs to do case insensitive comparisons of strings, use one or the other of these methods to convert the strings to a common case
53
Starting Out with Visual Basic.NET 2 nd Edition IsNumeric Function This function when applied to a string returns True if the string can be recognized as a number; False, otherwise Use it to determine if a given string is numeric data
54
Starting Out with Visual Basic.NET 2 nd Edition 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 = "Please 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
55
Starting Out with Visual Basic.NET 2 nd Edition Trimming Spaces from Strings There are three Methods that remove spaces from strings: TrimStart TrimEnd Trim greeting = " Hello " lblMessage1.Text = greeting.TrimStart ' Yeilds a value of "Hello "
56
Starting Out with Visual Basic.NET 2 nd Edition The Substring Method, I This Method returns a substring (a portion of another string) Substring(Start) returns a string with all of the characters from the original string starting at position Start Substring(Start, Length) returns the substring starting at Start of length Length
57
Starting Out with Visual Basic.NET 2 nd Edition The Substring Method, II For example: Dim firstName As String Dim fullName As String = "George Washington" firstName = fullName.Substring(0, 6) ' firstName has the value "George" ' fullName is unchanged
58
Starting Out with Visual Basic.NET 2 nd Edition Searching for a Character or a String within Another String, I Use one of these Methods: IndexOf(Searchstring) searches the entire string IndexOf(SearchString, Start) starts at the character position Start and searches from there IndexOf(SearchString, Start, Count) uses Start as above and then searches Count characters into the SearchString
59
Starting Out with Visual Basic.NET 2 nd Edition Searching for a Character or a String within Another String, II IndexOf will return the starting position of the SearchString in the string being searched Positions are numbered from 0 (for the first) If the SearchString is not found, a -1 is returned Dim name As String = "Angelina Adams" Dim position As Integer position = name.IndexOf("A", 1) ' position has the value 9 Position 0 Position 9
60
Starting Out with Visual Basic.NET 2 nd Edition 4.9 The Message Box Sometimes You Need a Convenient Way to Display a Message to the User This Section Introduces the Messagebox.Show Method, Which Allows You to Display a Message in a Dialog Box
61
Starting Out with Visual Basic.NET 2 nd Edition Messagebox.Show Arguments 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 Arguments are optional bottom to top
62
Starting Out with Visual Basic.NET 2 nd Edition Buttons Argument Value - Description 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.
63
Starting Out with Visual Basic.NET 2 nd Edition Example Message Box MessageBox.Show("Do you wish to continue?", _ "Please Confirm", _ MessageBoxButtons.YesNo)
64
Starting Out with Visual Basic.NET 2 nd Edition Which Button Was Clicked, I MessageBox returns a value indicating which button the user clicked: DialogResult.Abort DialogResult.Cancel DialogResult.Ignore DialogResult.No DialogResult.OK DialogResult.Retry DialogResult.Yes
65
Starting Out with Visual Basic.NET 2 nd Edition Which Button Was Clicked, II 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
66
Starting Out with Visual Basic.NET 2 nd Edition 4.10 The Select Case Statement In a Select Case Statement, One of Several Possible Actions Is Taken, Depending on the Value of an Expression
67
Starting Out with Visual Basic.NET 2 nd Edition Select Case Statement Example, I Select Case Val(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
68
Starting Out with Visual Basic.NET 2 nd Edition Select Case Statement Example, II Select Case animal 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
69
Starting Out with Visual Basic.NET 2 nd Edition 4.11 Input Validation Input Validation Is the Process of Inspecting Input Values and Determining Whether They Are Valid
70
Starting Out with Visual Basic.NET 2 nd Edition Validation Example ' Validate the input to ensure that ' no negative numbers were entered. If sales < 0 Or advance < 0 Then MessageBox.Show("Please enter positive numbers for " & _ " sales and/or advance pay.") EndIf
71
Starting Out with Visual Basic.NET 2 nd Edition 4.12 Radio Buttons and Check Boxes Radio Buttons Appear in Groups of Two or More, and Allow the User to Select One of Several Possible Options Check Boxes, Which May Appear Alone or in Groups, Allow the User to Make Yes/no or On/off Selections
72
Starting Out with Visual Basic.NET 2 nd Edition Checking Radio Buttons in Code If radChoice1.Checked = True Then MessageBox.Show("You selected Choice 1") ElseIf radChoice2.Checked = True Then MessageBox.Show("You selected Choice 2") ElseIf radChoice3.Checked = True Then MessageBox.Show("You selected Choice 3") End If
73
Starting Out with Visual Basic.NET 2 nd Edition Grouping Radio Buttons Radio Buttons are mutually exclusive in their container Therefore radio buttons are often put inside Group Boxes Each Group Box contains a set of radio buttons (so an option may be chosen from each set)
74
Starting Out with Visual Basic.NET 2 nd Edition Checking Check Boxes in Code If chkChoice4.Checked = True Then message = message & " and Choice 4" End If
75
Starting Out with Visual Basic.NET 2 nd Edition 4.13 Class-level Variables Class-level Variables Are Not Local to Any Procedure In a Form File They Are Declared Outside of Any Procedure, and May Be Accessed by Statements in Any Procedure in the Same Form
76
Starting Out with Visual Basic.NET 2 nd Edition Advantages of Class-level Variables The scope of class-level variables include all of the procedures below the declaration in the file Hence, with the use of class-level variables, communication of information between procedures is very easy
77
Starting Out with Visual Basic.NET 2 nd Edition Issues with Class-level Variables Class-level variables should be used sparingly - only when really needed. Why? In larger programs, the uses of these variables will be more difficult to keep track of and hence tend to introduce bugs into the procedures Class-level variables never need be passed as arguments to a method of the same class
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.