IS 350 Decision-making.

Slides:



Advertisements
Similar presentations
Lists, Loops, Validation, and More
Advertisements

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 5- 1 STARTING OUT WITH Visual Basic 2008 FOURTH EDITION Tony Gaddis.
CS0004: Introduction to Programming Select Case Statements and Selection Input.
1.
Microsoft Visual Basic: Reloaded Chapter Five More on the Selection Structure.
CSC110 Fall Chapter 5: Decision Visual Basic.NET.
VB.Net Decisions. The If … Then Statement If condition Then Statements End If If condition Then Statements Else Statements End If Condition: –Simple condition:
IS 1181 IS 118 Introduction to Development Tools VB Chapter 03.
Microsoft Visual Basic 2008: Reloaded Fourth Edition
Chapter 4: The Selection Structure
Chapter 7 Decision Making. Class 7: Decision Making Use the Boolean data type in decision-making statements Use If statements and Select Case statements.
PROGRAMMING IN VISUAL BASIC.NET VISUAL BASIC BUILDING BLOCKS Bilal Munir Mughal 1 Chapter-5.
Chapter 4: The Selection Process in Visual Basic.
Chapter 4: The Selection Structure
Lecture Set 5 Control Structures Part A - Decisions Structures.
 2002 Prentice Hall. All rights reserved. 1 Chapter 5 – Control Structures: Part 2 Outline 5.1Introduction 5.2 Essentials of Counter-Controlled Repetition.
T U T O R I A L  2009 Pearson Education, Inc. All rights reserved. 1 8 Dental Payment Application Introducing CheckBox es and Message Dialogs.
Microsoft Visual Basic 2008: Reloaded Third Edition Chapter Five More on the Selection Structure.
Decisions and Debugging Part06dbg --- if/else, switch, validating data, and enhanced MessageBoxes.
CHAPTER FIVE Specifying Alternate Courses of Action: Selection Statements.
T U T O R I A L  2009 Pearson Education, Inc. All rights reserved Security Panel Application Introducing the Select Case Multiple-Selection Statement.
Chapter 5: More on the Selection Structure
Visual Basic 2010 How to Program © by Pearson Education, Inc. All Rights Reserved.1.
1 Week 5 More on the Selection Structure. 2 Nested, If/ElseIf/Else, and Case Selection Structures Lesson A Objectives After completing this lesson, you.
Visual Basic 2010 How to Program © by Pearson Education, Inc. All Rights Reserved.1.
 2008 Pearson Education, Inc. All rights reserved JavaScript: Introduction to Scripting.
5.1 Introduction Problem Solving –Requires understanding of: Building blocks Program-construction principles BZUPAGES.COM.
T U T O R I A L  2009 Pearson Education, Inc. All rights reserved Student Grades Application Introducing Two-Dimensional Arrays and RadioButton.
Controlling Program Flow with Decision Structures.
Microsoft Visual Basic 2012 CHAPTER FOUR Variables and Arithmetic Operations.
 2002 Prentice Hall. All rights reserved. 1 Chapter 5 – Control Structures: Part 2 Outline 5.1Introduction 5.2 Essentials of Counter-Controlled Repetition.
Clearly Visual Basic: Programming with Visual Basic 2008 Chapter 11 So Many Paths … So Little Time.
An Introduction to Programming with C++ Sixth Edition Chapter 5 The Selection Structure.
Visual Basic Declaring Variables Dim x as Integer = 0 In the statement above, x is being declared as an Integer (whole number) and is initialised.
Computer Science Up Down Controls, Decisions and Random Numbers.
VISUAL BASIC 6.0 Designed by Mrinal Kanti Nath.
Visual Basic.NET Windows Programming
A variable is a name for a value stored in memory.
Programming in visual basic .net Visual Basic Building Blocks
Chapter 4 The If…Then Statement
IS 350 Application Structure
Apply Procedures to Develop Message, Input, and Dialog Boxes
Chapter 4: Making Decisions.
Lists, Loops, Validation, and More
The Selection Structure
Introduction to Scripting
Chapter 4: The Selection Structure
Topics The if Statement The if-else Statement Comparing Strings
Chapter 4: Making Decisions.
Chapter 5 – Control Structures: Part 2
Programming with Microsoft Visual Basic 2008 Fourth Edition
Chapter 2 Visual Basic Interface
CHAPTER FIVE Decision Structures.
Variables and Arithmetic Operations
Making Decisions in a Program
Topics The if Statement The if-else Statement Comparing Strings
Lesson 04 Control Structures I : Decision Making
WEB PROGRAMMING JavaScript.
Part A – Doing Your Own Input Validation with Simple VB Tools
Chapter 3: Introduction to Problem Solving and Control Statements
Part B – Structured Exception Handling
CIS 16 Application Development Programming with Visual Basic
Control Structures Part B - Message and Input Boxes
Microsoft Visual Basic 2005: Reloaded Second Edition
Chapter 3: Selection Structures: Making Decisions
Boolean Expressions to Make Comparisons
Chapter 3: Selection Structures: Making Decisions
Chapter 4 Decisions and Conditions
Presentation transcript:

IS 350 Decision-making

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

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

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

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

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

Boolean Assignment Statements The keywords True and False are used in Boolean assignment statements Example: Dim Valid As Boolean Valid = True Valid = False

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

Decision-making (pseudocode) If the input date is greater than today then Display a message indicating the input is invalid. End of If statement

Flowchart of a decision-making statement

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

Comparison Operators Equal to (=) Not equal to (<>) Less than (<) Greater than (>) Less than or equal to (<=) Greater than or equal to (>=)

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

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

Evaluating a condition

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

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

One-Way If Statement (example) Dim CurrentValue As Boolean = True If CurrentValue = True Then ' Statements that execute when ' CurrentValue is True End If ' statements

One-Way If statement

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

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

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

String equality using text and binary comparison

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

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

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

Two-way If statement

Introduction to Multiway If Statements Multiway If statements have three or more possible outcomes

Multiway If Statements (syntax) If condition1 Then [statements] [ElseIf condition2 Then [elseifStatements]] [Else] [elseStatements]] End If statements

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

Multiway If statement

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

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

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

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

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

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

Select Case statement

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

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

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

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

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

The Not Operator The Not operator is a unary operator Examples: Result = Not (True) ' False Result = Not (False) ' True Result = Not (4 > 3) ' False

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

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

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

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

Message box

Message box enumerations

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

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

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)

Input box

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

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

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

Focus and Validating event sequence

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

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

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

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

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

Execution flow of a structured exception handler

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

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

.NET Framework exception hierarchy

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

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

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

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

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

Changing the Value property of a vertical scroll bar

The Maximum and Minimum properties of a vertical scroll bar

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

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

The GroupBox Control (syntax) The BackColor and ForeColor properties define the color Visual text appears in the Text property

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

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

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

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

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