Download presentation
Presentation is loading. Please wait.
1
IS 350 Decision-making
2
Objectives Use the Boolean data type in decision-making statements
Write If statements and Select Case statements to make decisions Use logical operators to create complex conditions Create message boxes and input boxes Use decision-making statements to perform input validation
3
Objectives (continued)
Create structured exception handlers so that run-time errors will not cause an application to terminate Create instances of check boxes, scroll bars, group boxes, and radio buttons Group control instances
4
Introduction to Decision Making
Chapter 1 introduced the three control structures Sequence structure Decision-making structure Repetition structure This chapter discusses the decision-making structure Statements execute conditionally based on the outcome of a decision
5
Introduction to Boolean Data
Boolean data operates similarly to an on/off switch True signifies on False signifies off Many properties store Boolean data Visible and Enabled for example
6
Declaring a Boolean Variable
Declare a Boolean variable Uninitialized Boolean variables have a value of False Dim Valid As Boolean Declare and initialize a Boolean variable Dim BrowseMode As Boolean = True Declare multiple Boolean variables Dim Test1, Test2 As Boolean
7
Boolean Assignment Statements
The keywords True and False are used in Boolean assignment statements Example: Dim Valid As Boolean Valid = True Valid = False
8
Introduction to Decision Making
Applications need the capability to execute one group of statements in certain circumstances and other statements in other circumstances These statements are called decision-making statements The If statement is used to make decisions
9
Decision-making (pseudocode)
If the input date is greater than today then Display a message indicating the input is invalid. End of If statement
10
Flowchart of a decision-making statement
11
Using If Statements and Comparison Operators
A conditional statement executes one group of statements when a condition is True and another group of statements when a condition is False Comparison operators are used in conditional statements Conditional operations always produce a Boolean result
12
Comparison Operators Equal to (=) Not equal to (<>)
Less than (<) Greater than (>) Less than or equal to (<=) Greater than or equal to (>=)
13
Using Comparison Operators (example 1)
Dim Result As Boolean Dim Value1 As Integer = 3, Value2 As Integer = 5 Result = Value1 < Value2 ' True Result = Value1 + 2 < Value2 – 1 ' False
14
Using Comparison Operators (example 2)
Parentheses can clarify the order of evaluation The following two statements are equivalent: Result = Value1 + 2 < Value2 – 1 Result = (Value1 + 2) < (Value2 – 1) Result = (3 + 2) < (5 – 1) Result = (5) < (5 – 1) Result = (5) < (4) Result = False
15
Evaluating a condition
16
Comparison Operators and If Statements
Comparison operators are most commonly used with an If statement A group of statements execute only when a condition is True This form of If statement is called a one-way If statement The statements that execute as a result of a condition are called a statement block
17
One-Way If Statement (Syntax)
If condition Then statements End If statement condition must evaluate to a Boolean value If the condition is True, statements execute If the condition is False, statements do not execute Execution continues at the statement following the End If statements make up a statement block
18
One-Way If Statement (example)
Dim CurrentValue As Boolean = True If CurrentValue = True Then ' Statements that execute when ' CurrentValue is True End If ' statements
19
One-Way If statement
20
Comparison Operations Involving Dates
Comparison operations can be performed on dates Dates in the past are less than dates in the future Example: Dim StartDate As DateTime = #3/22/2010# Dim EndDate As DateTime = #3/24/2010# If StartDate < EndDate = True Then Console.WriteLine( _ "StartDate is less than EndDate") End If
21
Comparison Operations on Numeric Data Types
Comparison operations can be performed on numeric data Example: Dim Percentage As Integer = 90 If Percentage < 100 Then Console.Writeline( _ "Percentage is less than 100") End If ' statements
22
Comparison Operations on Strings
Comparison operations can be performed on strings Strings are compared character-by-character from left to right String comparisons are performed in two ways Case sensitive (binary comparison) 1 < 9 < A < B < E < Z < a < b < e < z Option Compare Binary Case insensitive (text comparison) 1 < 9 < (A=a) < (B=b) < (E=e) < (Z=z) Option Compare Text
23
String equality using text and binary comparison
24
Introduction to Two-way If Statements
One statement block executes when a condition is True and another statement block executes when the condition is False This form of If statement is commonly referred to as an If Then Else statement
25
Two-way If Statements (syntax)
If condition Then statements(True) Else statements(False) End If statements Statements(True) execute if the condition is True Statements(False) execute if the condition is False
26
Two-way If Statements (example)
If Grade is greater than 75, display “Passing grade”. Otherwise, display “Failing grade” Dim Grade As Integer = 80 If Grade > 75 Then Console.WriteLine("Passing grade") Else Console.WriteLine("Failing grade") End If ' statements
27
Two-way If statement
28
Introduction to Multiway If Statements
Multiway If statements have three or more possible outcomes
29
Multiway If Statements (syntax)
If condition1 Then [statements] [ElseIf condition2 Then [elseifStatements]] [Else] [elseStatements]] End If statements
30
Multiway If Statements (dissection)
condition1 is first tested If True, then the first statement block executes Execution continues at the statement following the decision-making statement If False, condition2 is tested, and then the remaining conditions are tested If no conditions are True, then the statements in the Else block execute The Else block is optional
31
Multiway If statement
32
Multiway If Statement (example)
Dim NumericGrade As Integer = 84 Dim LetterGrade As String If NumericGrade >= 90 Then LetterGrade = "A" ElseIf NumericGrade >= 80 Then LetterGrade = "B" ElseIf NumericGrade >= 70 Then LetterGrade = "C" ElseIf NumericGrade >= 60 Then LetterGrade = "D" Else LetterGrade = "F" End If ' statements
33
Notes About If Statements
If statements can be written in different ways Chose the If statement that is most readable This decision can be subjective The Code Editor automatically indents blocks in an If statement The Code Editor automatically inserts the End If If statements can be nested One If statement can contain another If statement
34
Introduction to Select Case Statements
Select Case statements are similar to multiway If statements The same expression must be used in each condition Select Case statements are faster than comparable multiway If statements Select Case statements tend to be more readable than comparable multiway If statements
35
Select Case Statement (syntax)
Select Case testExpression Case expressionList-1 statement-block1 [Case expressionList-2 statement-block2] [Case expressionListn statement-blockn] [Case Else statements] End Select ' statements
36
Select Case Statement (dissection)
testExpression is evaluated once Each expressionList is then tested. If True, the corresponding statement-block executes and the Select Case statement ends Each expressionList is tested in-order When an expressionList is found to be True, the statement block executes and the Select Case statement ends If no expessionList is True, then the statements in the Case Else block execute
37
Select Case Statement (example)
Dim Quarter As Integer = 1 Dim QuarterString As String Select Case Quarter Case 1 QuarterString = "First" Case 2 QuarterString = "Second" Case 3 QuarterString = "Third" Case 4 QuarterString = "Fourth" Case Else QuarterString = "Error" End Select ' statements
38
Select Case statement
39
Select Case Statement (variations)
The To clause is used to test a range of values Case 90 To 100 The Is clause is used with comparison operators Case Is > 90 A list of values can be created with a comma separated list Case 1, 3, 5
40
Logical Operators (introduction)
Logical operators are used in conjunction with comparison and arithmetic operators Logical operators perform the same task as a conjunction (and) or a disjunction (or) in English The logical operators are And, Or, Not, Xor See Table 7-2 for examples
41
Logical Operators (precedence)
Logical operators have an order of precedence Arithmetic operators are evaluated first Comparison operators are evaluated second Logical operators are evaluated last from left to right in the following order: Not, And, Or, Xor
42
Logical Operators (example 1)
Evaluation of an expression: Dim Result As Boolean Result = (3 + 4) > 6 And (4 + 1) < 6 Result = 7 > 6 And 5 < 6 Result = True And True Result = True
43
Logical Operators (example 2)
Evaluation of an expression using And and Or Result = (7 > 9) Or (5 > 3) And (3 > 2) Result = False Or True And True Result = False Or True Result = True
44
The Not Operator The Not operator is a unary operator Examples:
Result = Not (True) ' False Result = Not (False) ' True Result = Not (4 > 3) ' False
45
Using Logical Operators
Logical operators are typically combined with comparison and arithmetic operators in decision-making statements Example: If Input >= CurrentMin And _ Input <= CurrentMax Then Valid = True Else Valid = False End If ' statements
46
Introduction to the MessageBox Class
The MessageBox is a standard dialog box that displays A message A caption An icon One or more standard button groups
47
The MessageBox Show Method (syntax)
Public Shared Function Show(ByVal text As String, ByVal caption As String, ByVal buttons As MessageBoxButtons, ByVal icon As MessageBoxIcon) As DialogResult text appears in the title bar caption contains the message buttons defines the button(s) icon defines the icon
48
The MessageBox.Show Method (example)
Display a message box with Yes and No buttons Dim Result As DialogResult Result = MessageBox.Show( _ "Do you want to quit?", "Exit", _ MessageBoxButtons.YesNo, _ MessageBoxIcon.Question, _ MessageBoxDefaultButton.Button1) If Result = DialogResult.Yes Then Me.Close() End If
49
Message box
50
Message box enumerations
51
The InputBox (introduction)
The InputBox method gets a text string from the end user It's a standard dialog box It is possible to supply a default textual value
52
The InputBox (syntax) prompt contains a descriptive prompt
Shared Function InputBox(ByVal prompt As String, Optional ByVal title As String, Optional ByVal defaultResponse As String, Optional ByVal xPos As Integer, Optional ByVal yPos As Integer) As String prompt contains a descriptive prompt title appears on the title bar defaultResponse contains the default value xPos and YPos contain the coordinate values where the input box will appear
53
The InputBox (example)
Display an input box and store the returned string in ResultString Dim ResultString As String ResultString = _ Microsoft.VisualBasic.InputBox( _ "Enter a value", "Title", _ "Default Value", 0, 0)
54
Input box
55
Decision Making and Input Validation (1)
Input validation is used to check input to make sure it is valid or at least plausible Use the IsDate function to determine whether a string can be converted to a date Use the IsNumeric function to determine whether a string can be converted to a number These functions return True if the value can be converted and False otherwise The methods do not actually convert the value
56
Decision Making and Input Validation (continued)
Use range checking to determine whether a value falls between a range of values A person's age, for example The format of some data can be validated Social Security numbers Telephone numbers Zip codes
57
Input Validation Events
The Validating event fires just before a control instance loses focus This event can be cancelled The Validated event does not fire in this case If the Validating event is not canceled, the Validated event fires
58
Focus and Validating event sequence
59
Validating Event (example)
Validate a text box and cancel the event if the contents are invalid Private Sub txtDOB_Validating( _ ByVal sender As Object, _ ByVal e As _ System.ComponentModel.CancelEventArgs) _ Handles txtDOB.Validating If Not (IsDate(txtDOB.Text)) Then e.Cancel = True End If End Sub
60
Introduction to Structured Exception Handling
Run-time errors will cause a program to terminate because of an exception being thrown Exceptions can be thrown for several reasons Numeric overflow errors Type conversion errors Division by zero errors Create structured exception handlers to prevent a program from terminating
61
Structured Exception Handlers (syntax)
Try ' Place executable statements that might throw ' an exception in this block. Catch ' This code runs if the statements in the Try ' block throw an exception. Finally ' This code always runs after ' the Try block or Catch block exits. End Try
62
Structured Exception Handlers (syntax dissection)
The Try statement marks the beginning of an exception handler Place the statement(s) that may cause an exception in the Try block The Catch statement contains the code that executes if an exception is thrown Multiple Catch blocks can be created The statements in the optional Finally block always execute
63
Structured Exception Handler (example)
Handle all exceptions and display a message box, if necessary Dim Value1 As Short = 100 Dim Value2 As Short = 0 Dim Result As Short Try Result = Value1 \ Value2 Catch MessageBox.Show("Division by zero", "Error", _ MessageBoxButtons.OK, _ MessageBoxIcon.Information) End Try
64
Execution flow of a structured exception handler
65
The System.Exception Class
All exceptions are derived from the System.Exception class Properties The Message property contains an informational message The Source property is a string containing the name of the application causing the error The StackTrace property returns a string containing the error location
66
Types of Exceptions ArithmeticException can be thrown because of type conversion errors DivideByZeroException is thrown when trying to divide a number by zero OverflowExcpetion is thrown in cases of numeric overflow Trying to reference an object that does not exist throws a NullReferenceException
67
.NET Framework exception hierarchy
68
Controls that Rely on Decision-Making
Three controls are commonly used with decision-making CheckBox control allows the end user to select one of two possible values HScrollBar control and VScrollBar controls allow the end user to select a value from a range of values
69
The CheckBox Control The CheckBox control allows the end user to select from two possible values (Checked and Unchecked) CheckAlign property defines where the check box appears Boolean Checked property indicates whether the box is checked Text property contains the visible text TextAlign property controls the alignment of the text CheckedChanged event fires when the value of the Checked property changes
70
The CheckBox Control (example)
Determine whether the CheckBox named chkDemo is checked If chkDemo.Checked = True Then Console.WriteLine("Checked") Else Console.WriteLine("Not checked") End If
71
The HScrollBar and VScrollBar Controls (ontroduction)
Use to select a value from a range of values The two scroll bars work the same way HScrollBar has a horizontal orientation VScrollBar has a vertical orientation
72
The HScrollBar and VScrollBar Controls (syntax)
Minimum and Maximum properties define the range of values Current value is stored in the Value property SmallChange and LargeChange properties define the magnitude of change Scroll event fires while scrolling ValueChanged event fires when scrolling is complete and the value changes
73
Changing the Value property of a vertical scroll bar
74
The Maximum and Minimum properties of a vertical scroll bar
75
Scroll Event (example)
Display scroll bar values Private Sub vsbDemo_Scroll( _ ByVal sender As System.Object, _ ByVal e As _ System.Windows.Forms.ScrollEventArgs) _ Handles vsbDemo.Scroll txtValue.Text = vsbDemo.Value.ToString() txtOldValue.Text = e.OldValue.ToString() txtNewValue.Text = e.NewValue.ToString() End Sub
76
Control Groups Container controls are used to group control instances together The GroupBox control is a container control Visual Studio supports several other container controls
77
The GroupBox Control (syntax)
The BackColor and ForeColor properties define the color Visual text appears in the Text property
78
The RadioButton Control
The end user selects one button from a group of buttons Members The Text property contains the visible text The Checked property defines whether the RadioButton is selected The CheckedChanged event fires when the button is clicked
79
Multicast Event Handlers (introduction)
One event handler handles the same event for many control instances The Handles clause contains a comma separated list of control instances and event names A period separates the control instance and event name
80
Multicast Event Handlers (Example)
Handle the CheckChanged event for three radio buttons Private Sub radChoices_CheckedChanged( _ ByVal sender As System.Object, _ ByVal e As System.EventArgs) _ Handles radFirstChoice.CheckedChanged, _ radSecondChoice.CheckedChanged, _ radThirdChoice.CheckedChanged Dim CurrentRadioButton As RadioButton CurrentRadioButton = CType(sender, RadioButton) Select Case CurrentRadioButton.Name Case "radFirstChoice" Case "radSecondChoice" Case "radThirdChoice" End Select End Sub
81
Chapter Summary The Boolean data type stores values of True and False
Decision-making statements are categorized into one-way, two-way and multiway If statements Conditional statements are made up of arithmetic, comparison, and logical operators In cases where an expression is compared with different values, a Select Case statement can be used in place of a multiway If statement
82
Chapter Summary (continued)
The MessageBox and InputBox classes are used to display standard dialog boxes Structured exception handlers are a form of decision-making statement used to handle errors The CheckBox, HScrollBar, and VScrollBar controls are used to work with Boolean data Container controls, such as the GroupBox, group other control instances A multicast event handler is often used with RadioButtons to handle events for multiple control instances
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.