Sie sind auf Seite 1von 34

Visual Basic.

Net
Selections Construct
Objectives

• This lecture will cover:


– identifying conditions and actions in specifications
– constructing algorithms containing decisions
– using comparison and logical operators
– If statements in Visual Basic
– Select statements in Visual Basic
– testing and debugging selections
– generating random numbers

Visual Basic Slide 2 of 42


Selection

• The Selection construct is used for branching of


actions to be perform depending on a condition
are used to give an application decision making
capabilities.
• There are three selection constructs used in
programming
– If...Then
– If …Then…Else
– Select…Case

Visual Basic Slide 3 of 42


Conditions

• A condition is a comparison between one value


against another
• Uses comparison operators (a.k.a. Relational
Operator)
• May combine results of several comparisons
using logical operators

Visual Basic Slide 4 of 42


Comparison operators

• Relational (a.k.a. Comparison) Operators


include:
= equal to
<> not equal to
> greater than
< less than
>= greater than or equal to
<= less than or equal to
• Can only be used on primitive data types
• String comparisons use ANSI values and upper
case letters will precede lower case

Visual Basic Slide 5 of 42


Logical operators

• Used to combine results of different tests


• Brackets can be used to clarify meaning
– AND True if all parts are True
– OR True if any part is True
– NOT negates the result
• Each condition part must be correctly formed

Visual Basic Slide 6 of 42


APIIT City Campus –
2008 Feb – Last

Logical Operator - AndAlso


Modified by Nadeera
Ahangama.

• The AndAlso operator returns False when


the condition on the left hand side is
False.
• Else, it returns True when the conditions
of the left and right are True.
• Otherwise, it returns False.
• The condition on the right hand side is
never evaluated when that on the left hand
side is False.
• This is called short-circuited logic.

Visual Basic
APIIT City Campus –
2008 Feb – Last

AndAlso - Truth Table


Modified by Nadeera
Ahangama.

Condition1 Condition2 Condition1 AndAlso Condition2

True True True

True False False

False - False

Visual Basic
APIIT City Campus –
2008 Feb – Last

Logical Operator - Or
Modified by Nadeera
Ahangama.

• The Or operator returns True when the


condition on either side is True.
• Otherwise, it returns False.
• Both conditions are evaluated before the
result is returned.

Visual Basic
APIIT City Campus –
2008 Feb – Last

Or - Truth Table
Modified by Nadeera
Ahangama.

Condition1 Condition2 Condition1 Or Condition2

True True True

True False True

False True True

False False False

Visual Basic
APIIT City Campus –
2008 Feb – Last

Logical Operator - OrElse


Modified by Nadeera
Ahangama.

• The OrElse operator returns True when


the condition on the left hand side is
True.
• Else, if the condition on the right hand
side is True, it returns True.
• Otherwise, it returns False.
• The condition on the right hand side is
never evaluated when that on the left
hand side is True.
• This is called short-circuited logic.
Visual Basic
APIIT City Campus –
2008 Feb – Last

OrElse - Truth Table


Modified by Nadeera
Ahangama.

Condition1 Condition2 Condition1 OrElse Condition2

True - True

False True True

False False False

Visual Basic
APIIT City Campus –
2008 Feb – Last

Logical Operator - Xor


Modified by Nadeera
Ahangama.

• The Xor operator returns True when the


condition on the left hand side or right
hand side is True, but not when both are
True.
• Xor means "Exclusive OR".

Visual Basic
APIIT City Campus –
2008 Feb – Last

Xor - Truth Table


Modified by Nadeera
Ahangama.

Condition1 Condition2 Condition1 Xor Condition2

True True False

True False True

False True True

False False False

Visual Basic
IF statement

• Powerful language construct


• Evaluates condition and performs different
operations based on the outcome
• Terminated by a matching End If
• VB.Net will automatically indents the code to
show structure

Visual Basic Slide 15 of 42


One-way selection

• performs actions when a condition is true

If <condition> Then
<statements>
End If

Visual Basic Slide 16 of 42


One-way selection – Single line

• performs actions when a condition is true

If <condition> Then <statement>

Visual Basic Slide 17 of 42


Example

• In an application, users are required to


guess a random number between 1 and
10.
• If the number is correctly guessed, the
application will display a message on a
label. If wrongly guessed, another
message will be displayed, and the correct
number is revealed on the same label

Visual Basic Slide 18 of 42


Guess Number

txtGuess

lblAns

btnGuess

Visual Basic Slide 19 of 42


Coding
Public Class frmNumGuess lblAnswer.Text = "Congratulation!
Dim SecretNum As New Random ' create You have guessed the correct
a random generator object number!"
Private Sub btnGuess_Click(ByVal End If
sender As System.Object, ByVal e As
System.EventArgs) Handles 'otherwise, informs the user that the
btnGuess.Click guess fails and let the user try
Dim myNum, guess As Integer ' again using another number (tough
game huh!! XD)
' generates a random number between If guess <> myNum Then
‘1 and 10 lblAnswer.Text = "Sorry, you have
' and store that number into myNum guessed incorrectly. The correct
myNum = SecretNum.Next(1, 10) number is " & myNum
txtGuess.Clear()
'gets the input value from the user txtGuess.Focus()
guess = Integer.Parse(txtGuess.Text) End If
'compares if the number entered is
the same as the random number End Sub
' if the numbers are same, then user End Class
guessed correctly
If guess = myNum Then

Visual Basic Slide 20 of 42


Two-way selection

• Executes one set of statements if condition is


true and another if it is false

If <condition> Then
<statements1>
Else
<statements2>
End If

Can alter condition and swap statements in


the If block and Else block

Visual Basic Slide 21 of 42


Example – Ticket Seats

• Ticket seats for a concert are categorized as


Lawn, Promenade and Balcony. The price for
balcony seats is $75, promenade seats is $30
and for lawn seats is $20.
• Write a program to determine the total price a
customer needs to pay for the tickets.
• Use radio buttons for the type of seat selection
as one customer may buy only one type of seat
ticket.

Visual Basic Slide 22 of 42


Screen Layout

txtQty

radBalc
radProm
radLawn

lblTotal

btnCalc btnExit
Visual Basic Slide 23 of 42
Coding to Calculate the Total Price

Private Sub btnCalc_Click(ByVal sender As System.Object, ByVal e As


System.EventArgs) Handles btnCalc.Click
Dim total As Decimal
If radBalc.Checked = True Then
price = 75.0
ElseIf radProm.Checked = True Then
price = 30.0
ElseIf radBalc.Checked = True Then
price = 20.0
End If
total = Integer.Parse(txtQty.Text) * price
lblTotal.Text = total.ToString("C")
End Sub

Visual Basic Slide 24 of 42


Multiple selection

• Used for multiple selections based on different


conditions
If <condition1> Then
<statements1>
ElseIf <condition2>Then
<statements2>
ElseIf <condition3>Then
<statements3>
Else
<statements4>
End If

Visual Basic Slide 25 of 42


Nested selection

• Actions in selections can be other selections


If txtSex.Text = "Male" Then
If txtAge.Text >= 65 Then
lblPension.Text = "Eligible male"
Else
lblPension.Text = "Ineligible male"
End If
Else
'similar test for female
End If

Visual Basic Slide 26 of 42


Select statement

• Alternative to If for mutually exclusive options


• Can only evaluate one expression to compare against the
available test case(s).

Select Case <testExpression>


Case <expression 1>
<statements 1>
Case <expression 2>
<statements 2>
Case Else
<statements n>
End Select

Visual Basic Slide 27 of 42


Case clause

Case clause can take following forms:


– a literal
– several comma-separated literals
– a range in the form of a To b (E.g. “a” To “e”)
– an inequality preceded by Is and followed by a literal,
variable or expression
Benefits of using Select statement:
– reduction in the amount of coding required
– increased efficiency
– improved readability of the code

Visual Basic Slide 28 of 42


Example

• Modify the Ticket Seats program to use


the Select Case structure

Visual Basic Slide 29 of 42


Testing selections

• Vital to ensure all possible paths through a


program are tested
• Test plan must be designed
– Choose values to ensure all possible paths
are executed
– Need to check for values around boundaries
– With discrete values it is necessary to try
each possible value in a separate test

Visual Basic Slide 30 of 42


Documenting test plan

• Not sufficient to just run the program with


carefully selected data
• Test plan should show:
– the data to be used
– the reason for the test
– the expected result
– the actual result
• If actual results are not as expected:
– program will probably need to be corrected
– tests rerun

Visual Basic Slide 31 of 42


Debugging selections

• Can attach a breakpoint to a condition


• When breakpoint is reached:
– debugger enters Break mode
– line highlighted in yellow
• Programmer can:
– hold cursor over variables to determine their current
values
– step through a line at a time, tracing the execution
path at run time

Visual Basic Slide 32 of 42


Random numbers

• Each value chosen can not be predicted


• Random class is used to generate random
numbers
• Must first declare a Random object
Dim <objectname> As New Random
• Next method is an overloaded method that
– Generates a random number that requires 2
parameters:
• minimum value and the maximum value
• <objectname>.Next(minValue, maxValue)
– Generates a random number that does not take in
any parameters
• <objectname>.Next()

Visual Basic Slide 33 of 42


Summary

• This lecture covered:


– identifying conditions and actions in specifications
– constructing algorithms containing decisions
– using comparison and logical operators
– If statements in Visual Basic
– Select statements in Visual Basic
– testing and debugging selections
– generating random numbers

Visual Basic Slide 34 of 42

Das könnte Ihnen auch gefallen