0% found this document useful (0 votes)
5 views

JK VB NET 5 Decision Making Structures

JK VB NET 5 Decision Making Structures

Uploaded by

curtisandrea242
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

JK VB NET 5 Decision Making Structures

JK VB NET 5 Decision Making Structures

Uploaded by

curtisandrea242
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 63

Decision making structures

Topics
• This presentation covers the Visual
Basic .NET decision statements
• If … Then
• ElseIf
• Case statement
• It also discusses the use of
• Radio Buttons and check boxes
• Message Boxes
The Decision Structure

The Decision Structure Allows a


Program to Have More Than One
Path of Execution
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 presentation)
• Repeat sections of code (next lesson)
The Decision Structure if….Then

• Flowchart of a
typical decision
structure True
Condition
• Evaluate the
False
condition
Conditional
• Execute, or not Code
some code
• Dim age As Integer
• age = txtage.Text
• If age >= 18 Then
• lbloutput.Text = "you can vote"
• End If
The If…Then Statement

The If…Then Statement Causes


Other Statements to Execute Only
Under a Certain Condition
If…Then Statement Syntax

If condition Then
statement
(more statements as needed)
End If

• New keywords used above:


• If
• Then
• End
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
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
If…Then Examples
Public Class Form1

Private Sub btnVote_Click(sender As Object,


e As EventArgs) Handles btnVote.Click

Dim age As Integer = 20


If age >= 18 Then
lblvote.Text = "you can vote "
End If

End Sub
End Class
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'
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
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
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
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
'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)
The 'If…Then…Else' Structure

False True
Condition

Execute Execute
If False If True
'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
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
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
More Than Two
Mutually Exclusive Choices

• The 'If…Then…ElseIf' statement provides a

series of mutually If
exclusive choices
it is very cold Then
• In pseudo code: 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
In Visual Basic .NET Syntax
If condition1 Then
Statement(s)1
Elseif condition2 Then
Statements(s)2
Elseif condition3 Then
Statements3

End If
In Flowchart Form

True
C1 Statement(s)1
False

True
C2 Statement(s)2
False
True
C3 Statement(s)3
False
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
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:
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
Logical Operators

Logical Operators Connect Two or


More Relational Expressions Into
One, or Reverse the Logic of an
Expression
Visual Basic .NET Logical Operators

Operator Effect
And Both 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
The 'And' Operator
Truth Table for 'And' Operator
Expression 1 Expression 2 Expression 1 And Expression 2
True False False
False True False
False False False
True True True

If marks < 0 And marks > 40 Then


lblMessage.Text = “Poor perfomance."
End If
The 'Or' Operator
Truth Table for 'Or' Operator
Expression 1 Expression 2 Expression 1 Or Expression 2
True False True
False True True
False False False
True True True

If marks < 40 Or marks > 70 Then


lblMessage.Text = “Average performance."
End If
The 'Xor' Operator
Truth Table for 'Xor' Operator
Expression 1 Expression 2 Expression 1 Xor Expression 2
True False True
False True True
False False False
True True False

If total > 1000 Xor average > 120 Then


lblMessage.Text = “You may try again."
End If
The 'Not' Operator

Truth Table for 'Not' Operator


Expression 1 Not Expression 1
True False
False True

If Not temperature > 100 Then


lblMessage.Text = "You are below the maximum temperature."
End If
Checking Numerical Ranges

• Checking for a value inside of a range:


If x >= 20 And x <= 40 Then
lblMessage.Text = "The value is in the acceptable range."
End If

• Checking for a value outside of a range:

If x < 20 Or x > 40 Then


lblMessage.Text = "The value is outside the acceptable range."
End If
Relative Precedence
of the Logical Operators

• From highest to lowest precedence


• Not (unary + and -)
• The binary arithmetic operators
• The relational operators
• And
• Or
• Xor
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'
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)
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
Messagebox.Show Arguments

• Message - text to display within the box


• Caption - title for the top bar of the box
• Buttonsgg - 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
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.
Example Message Box
MessageBox.Show("Do you wish to continue?", _
"Please Confirm", _
MessageBoxButtons.YesNo)
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
Which Button Was Clicked, II
The Select Case Statement

In a Select Case Statement, One of Several


Possible Actions Is Taken, Depending on the
Value of an Expression
Select Case Decision Structures
• With Visual Basic, you can also control the execution of
statements in your programs by using Select Case decision
structures
• A Select Case structure is similar to an If . . . Then . . .
ElseIf structure, but it’s more efficient when the branching
depends on one key variable, or test case. You can also use
Select Case structures to make your program code more
readable
The syntax for a Select Case structure
looks like this:
Select Case variable
Case value1
statements executed if value1 matches variable
Case value2
statements executed if value2 matches variable
Case value3
statements executed if value3 matches variable
...
Case Else
statements executed if no match is found
End Select
• A Select Case structure begins with the Select Case keywords
and ends with the End Select keywords You replace variable
with the variable, property, or other expression that is to be the
key value, or test case, for the structure.
• You replace value1, value2, and value3 with numbers, strings,
or other values related to the test case being considered.
• If one of the values matches the variable, the statements
below the Case clause are executed, and then Visual Basic
jumps to the line after the End Select statement and picks up
execution there .
• You can include any number of Case clauses in a Select Case
structure, and you can include more than one value in a Case
clause If you list multiple values after a case, separate them
with commas
• The following example shows how a Select Case structure
could be used to print an appropriate message about a
person’s age and cultural milestones in a program. Since the
Age variable contains a value of 18, the string “You can vote
now!” is assigned to the Text property of the label object.
Dim Age As Integer
Age = 18
Select Case Age
Case 16
Label1.Text = "You can drive now!"
Case 18
Label1.Text = "You can vote now!"
Case 21
Label1.Text = "You can drink wine with your meals."
Case 65
Label1.Text = "Time to retire and have fun!"
End Select
A Select Case structure also supports a Case Else clause that
you can use to display a message if none of the preceding cases
matches the Age variable. Here’s how Case Else
would work in the following example—note that I’ve changed
the value of Age to 25 to trigger the Case Else clause:
Dim Age As Integer
Age = 25
Select Case Age
Case 16
Label1.Text = "You can drive now!"
Case 18
Label1.Text = "You can vote now!"
Case 21
Label1.Text = "You can drink wine with your meals.“
Case 65
Label1.Text = "Time to retire and have fun!"
Case Else
Label1.Text = "You're a great age! Enjoy it!"
End Select
Using Comparison Operators with a Select Case Structure
You can use comparison operators to include a range of test values in a Select
Case structure
The Visual Basic comparison operators that can be used are =, <>, >, <, >=,
and <= .
To use the comparison operators, you need to include the Is keyword or the To
keyword in the expression to identify the comparison you’re making.
The Is keyword instructs the compiler to compare the test variable to the
expression listed after the Is keyword The To keyword identifis a range of
values The following structure uses Is, To, and several comparison
operators to test the Age variable and to display one of fie messages:
Select Case Age
Case Is < 13
Label1.Text = "Enjoy your youth!"
Case 13 To 19
Label1.Text = "Enjoy your teens!"
Case 21
Label1.Text = "You can drink wine with your meals."
Case Is > 100
Label1.Text = "Looking good!"
Case Else
Label1.Text = "That's a nice age to be."
End Select
• If the value of the Age variable is less than 13, the message
“Enjoy your youth!” is displayed
For the ages 13 through 19, the message “Enjoy your
teens!” is displayed, and so on …

• A Select Case decision structure is usually much clearer


than an If . . . Then structure and is more efficient when
you’re making three or more branching decisions based on
one variable or property However, when you’re making
two or fewer comparisons, or when you’re working with
several different values, you’ll probably want to use an
If . . . Then decision structure
Select Case Statement Example…

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
Input Validation

Input Validation Is the Process of


Inspecting Input Values and Determining
Whether They Are Valid
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
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
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
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)
Checking Check Boxes in Code

If chkChoice4.Checked = True Then


message = message & " and Choice 4"
End If
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
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
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

You might also like