Decisions and Conditions

Slides:



Advertisements
Similar presentations
1.
Advertisements

Objectives Understand the software development lifecycle Perform calculations Use decision structures Perform data validation Use logical operators Use.
Val Function A Function performs an action and returns a value The expression to operate upon, known as the argument, (or multiple arguments), must be.
Input Validation Check the values entered into a text box before beginning any calculations Validation is a form of ‘self-protection’, rejecting bad data.
Comparing Numeric Values If Val(Text1.Text) = MaxPrice Then (Is the current numeric value stored in the Text property of Text1 equal to the value stored.
CSC110 Fall Chapter 5: Decision Visual Basic.NET.
McGraw-Hill/Irwin Programming in Visual Basic 6.0 © 2002 The McGraw-Hill Companies, Inc. All rights reserved. Update Edition Chapter 4 Decisions and Conditions.
Input Validation Check the values entered into a text box before beginning any calculations Validation is a form of ‘self-protection’, rejecting bad data.
Dani Vainstein1 VBScript Session 9. Dani Vainstein2 What we learn last session? VBScript coding conventions. Code convention usage for constants, variables,
Variables and Constants
© 1999, by Que Education and Training, Chapter 5, pages of Introduction to Computer Programming with Visual Basic 6: A Problem-Solving Approach.
CIS162AD - C# Decision Statements 04_decisions.ppt.
Microsoft Visual Basic 2008: Reloaded Fourth Edition
Chapter 4: The Selection Structure
Saeed Ghanbartehrani Summer 2015 Lecture Notes #4: Working with Variables and User Interfaces IE 212: Computational Methods for Industrial Engineering.
JavaScript – Part II Data Types and Operations George Mason University June 3, 2010.
Chapter 4 P 1 Decisions and Conditions Control statements - seqeuncing - selection - repetition (picture later) - abstraction (procedure calls)
Chapter 4: The Selection Process in Visual Basic.
Chapter 4: The Selection Structure
Decisions and Debugging Part06dbg --- if/else, switch, validating data, and enhanced MessageBoxes.
Microsoft Visual Basic 2005: Reloaded Second Edition Chapter 3 Variables, Constants, Methods, and Calculations.
Input Validation Check the values entered into a text box before beginning any calculations Validation is a form of ‘self-protection’, rejecting bad data.
Visual Basic 2010 How to Program © by Pearson Education, Inc. All Rights Reserved.1.
Variables & Function Calls. Overview u Variables  Programmer Defined & Intrinsic  Data Types  Calculation issues u Using Functions  The val() function.
1 Scripting Languages VBScript - Recognized mainly by Internet Explorer only - Netscape does have a plug-in JavaScript - Recognized by Internet Explorer.
Irwin/McGraw-Hill Copyright© 2000 by the McGraw-Hill Companies, Inc. PowerPoint® Presentation to accompany prepared by James T. Perry University of San.
Computer-made Decisions Chapter 3 & 4. Overview u Variable Scope u Conditionals  Relational Operators  AND, OR, NOT u If Statements u MsgBox function.
Visual Basic for Application - Microsoft Access 2003 Programming applications using Objects.
Visual Basic 2010 How to Program © by Pearson Education, Inc. All Rights Reserved.1.
Chapter 4 Getting Started with VBA. Subroutines Subroutine is the logical section of code that performs a particular task. Subroutine is also called a.
CECS 5020 Computers in Education Visual Basic Variables and Constants.
Variables Continued In the last session we saw how variables are objects that allow us to store values in the RAM of the computer In this session we shall.
© by Pearson Education, Inc. All Rights Reserved.-Edited By Maysoon Al-Duwais 2.
Variables and Expressions Programming Right from the Start with Visual Basic.NET 1/e 7.
Controlling Program Flow with Decision Structures.
Microsoft Visual Basic 2012 CHAPTER FIVE Decision Structures.
Knowledge Base. Defining a Variable Dim statement Dim intXX As Integer Public in a Module Public dblNN As Double.
Creation of Variables with Numeric, alphanumeric, date, picture, memo data types Constant - A quantity that does not change during the execution of a program.
ME 142 Engineering Computation I Interacting with Spreadsheets.
An Introduction to Programming with C++ Sixth Edition Chapter 5 The Selection Structure.
Chapter 4.  Variables – named memory location that stores a value.  Variables allows the use of meaningful names which makes the code easier to read.
© 2006 Lawrenceville Press Slide 1 Chapter 4 Variables  A variable is a name for a value stored in memory.  Variables are created using a declaration.
Chapter 4: Decisions and Conditions
Egyptian Language School Computer Department
A variable is a name for a value stored in memory.
Chapter 4: Decisions and Conditions
Chapter 4: Making Decisions.
2.5 Another Java Application: Adding Integers
The Selection Structure
CHAPTER FIVE Decision Structures.
Chapter 4: The Selection Structure
Chapter 4: Making Decisions.
CHAPTER FIVE Decision Structures.
Variables and Arithmetic Operations
Making Decisions in a Program
Chapter 6 Variables What is VBScript?
Part A – Doing Your Own Input Validation with Simple VB Tools
Chapter 3: Introduction to Problem Solving and Control Statements
Objectives After studying this chapter, you should be able to:
VB Decisions, Conditions & If
Messages and Input boxes
Visual Basic Numbers Chapter 3.3 Prepared By: Deborah 1/15/2019.
Microsoft Visual Basic 2005: Reloaded Second Edition
VB Decisions & Conditions
Chapter 3: Selection Structures: Making Decisions
Boolean Expressions to Make Comparisons
Chapter 3: Selection Structures: Making Decisions
Visual Basic Numbers Chapter 3.3 Prepared By: Deborah 7/9/2019.
Introduction to Computer Programming IT-104
Presentation transcript:

Decisions and Conditions Chapter 4 Decisions and Conditions

Decisions and Conditions Block If statements Nested If statements Evaluating Conditions and Relational Operators Testing Values with option buttons & check boxes Validating input numeric fields Creating Message boxes Calling event procedures Debugging with breakpoints & stepping execution

Alternative courses of action are required in a program Decision Making Alternative courses of action are required in a program The IF statement provides one of these structures There are two types of IF statements Single-line IF statement Multi-line IF statement Single-line IF statement example: If txtUserResponse = “Yes” Then curTaxableIncome = 0 Multi-line IF statement example: If intDependentNumber > 2 Then lblAnswer.caption = “Two Dependents” Else lblAnswer.cpation = “Not Two Dependents” End If

Symbol Meaning > Greater than < Less than = Equal to Comparison Operators Symbol Meaning > Greater than < Less than = Equal to <= Less than or equal to >= Greater than or equal to <> Not equal to Expressions containing comparison operators always result in an answer that is either true or false. Example expressions using Visual Basic controls: txtName.text <> "Frockmeister" Val(txtAge.Text) > 25 optPrintForm.Value = True chkDiscardStyles.Value = False txtInterestRate.Text / 12 <= 0.05

IF Statement Structure (1) Sleepy? Go to bed True False Form: If condition Then statement(s) End If

IF Statement Structure (2) Is SAT > 600? Admit Do Not True False Form: If condition Then t-statement(s) Else f-statement(s) End If If Val(txtSat.text) > 600 Then Msgbox “Admit” Else Msgbox “Do Not Admit” End If

IF Statement Structure (3) Form: If condition-1 Then If condition-2 Then t-statement-2 Else f-statement-2 End If f-statement-1 End If False Is SAT > 600? Do Not Admit True Is GPA > 3.75? Consider If Val(txtSat.text) > 600 Then If Val(txtGPA) > 3.75 Then Msgbox “Admit” Else Msgbox “Consider” End if Msgbox “Do Not Admit” End If

Comparing Numeric Variables & Constants Comparing Strings Conditions Comparing Numeric Variables & Constants Comparing Strings Comparing text property of text boxes Uppercase and lowercase character comparisons Compound conditions When comparing values from text boxes with numeric values, be sure to first convert the text box data to a value. For example: If txtPrice.Text = curRetailPrice Then ... can result in an inaccurate comparison of a string and a currency value. Better to do this: If Val(txtPrice.Text) = curRetailPrice Then ... Also, if the text box is empty, then Val(textbox.text) is equal to zero. That can be very handy. It eliminates one possible error when you use a value in calculations When comparing strings, make sure you “negate” any potential problems with case not matching. Generally, you simply want the spelling to match. Compare these two slightly different conditions: If txtLastName.Text = “Smith” or If Lcase(txtLastName.Text) = “smith” You can use the logical operators of And, Or, and Not to form compound expressions such as: If (Ucase(txtLastName) = “SMITH” And Val(txtAge) > 25) Then... If (Val(txtAge.Text) = 0 Or txtLastName.Text = “”) Then ... Using parentheses around the conditional statement is optional but desirable

If & opt. buttons & check boxes If chkFlag = True Then imgFlag.Visible = True If optDisplayForm Then frmSecond.Show When using option button controls, you don't have to compare it against True or False in a conditional expression. Because the value of 0 is considered False and all other values (1, for example) are considered True. So, instead of writing this: If optPrintSelection = True Then ··· you can write the following equivalent statement: If optPrintSelection Then ··· The preceding is an example of an implied condition This can work for check boxes also, except check boxes can also have the value of 2 (undefined) When comparing a literal string to a text box value, always compare “apples to apples” by converting both to either uppercase or lowercase. That way you avoid a mismatch based solely on capitalization an not spelling: If txtLastName.Text = "Smith" Then … will evaluate to false if the txtLastName contains SmITH or smith. Better way is to always do this type of operation: If Ucase(txtLastName.Text) = "SMITH" Then ··· or If Lcase(txtLastName.Text) = "smith" Then ...

If a1 <= a2 or a3 > a4 and a5 < a6 Then Compound Conditions If a1 <= a2 or a3 > a4 and a5 < a6 Then And has precedence over Or All comparison operators have precedence over all logical operators Use parentheses to alter the order of evaluation Parentheses alter the order of evaluation and are good for explicitly documenting groupings or are good if you are unsure of precedence. If (curValue > 100) and (curValue < 200) Then lblMessage.Caption = "Value between 101 and 199" End If The following is a project called SimpleSample.vbp to illustrate the example on pages 137-138

"If" statement and option buttons

Displaying Messages in Message boxes Special window displaying message to user Form: MsgBox “message” [,buttons][, “t.b. caption”] Example: MsgBox “Numeric ID only”, vbOkOnly, “Error” Buttons/Icons you can display: Intrinsic Name Value Description vbOKOnly 0 OK button only (default). vbOKCancel 1 OK and Cancel buttons. vbAbortRetryIgnore 2 Abort, Retry, and Ignore buttons. vbYesNoCancel 3 Yes, No, and Cancel buttons. vbYesNo 4 Yes and No buttons. vbRetryCancel 5 Retry and Cancel buttons. vbCritical 16 Critical message. vbQuestion 32 Warning query. vbExclamation 48 Warning message. vbInformation 64 Information message. vbDefaultButton1 0 First button is default (default). vbDefaultButton2 256 Second button is default. vbDefaultButton3 512 Third button is default. vbApplicationModal 0 Application modal message box vbSystemModal 4096 System modal message box.

Displaying a Message String Use & to concatenate strings (“Concatenate” means join end to end) The VB intrinsic constant vbCRLF creates a new line in a string MsgBox stMessage, vbOKOnly, stTitle Dim stMessageString as String Dim stTitleBarString as String stMessageString = "The top salary is: " & vbCrLf & curTopSal & " for 2001" stTitleBarString = "Information for You" MsgBox stMessageString, vbOkOnly, stTitleBarString

Message box return values Constant Value Description vbOK 1 OK button pressed. vbCancel 2 Cancel button pressed. vbAbort 3 Abort button pressed. vbRetry 4 Retry button pressed. vbIgnore 5 Ignore button pressed. vbYes 6 Yes button pressed. vbNo 7 No button pressed. When you use the function form of the message box, you can save the returned value like this: iReturnedValue = MessageBox("Click a Button", vbYesNoCancel,"Test")

Checking a data type: IsNumeric & IsDate Input Validation Checking a data type: IsNumeric & IsDate IsNumeric checks & returns true or false If IsNumeric(txtQty.Text) Then lblDue.Caption = curPrice + Val(txtQty) Validating value ranges If Val(txtHours.Text) > 10 And _ Val(txtHours.Text) <= 80 Then ... Note that IsNumeric works on the Variant data type. The information in all text boxes is of type Variant—you can enter numbers of text values in a text box. Testing a text box with IsNumeric is always a good idea to prevent “surprises.”

Data Validation IsDate returns true or false depending on whether or not a value is a date If IsDate(txtData) Then … the VarType function return a number that corresponds to the data type stored in a variant. If VarType(varValue) = 0 Then... Here are the VarType values returned and each data type. Keep this for reference. Value Name Contents 0 Empty No data in the text box (.Text property is variant) 1 Null Variant has no value--not empty 2 Integer Whole number between -32767 and 32767 3 Long Whole number between -2Billion and +2Billion 4 Single Decimal number 5 Double Either a very big dec. numb. Or huge # dec. places 6 Currency Decimal number with 4 decimal places 7 Date/Time Value holding a particular date & time 8 String Text 9 OLE Object (ignore for now) 10 Error (ignore for now) 11 Boolean True or false value 12 Variant An array of variants 13 Object Code lump--a non-OLE object (ignore for now) 14 Decimal A power of 10 type number 17 Byte A binary value 8192 Array An ordered table of values

Using LostFocus to Validate LostFocus is a way to validate check boxes before allowing user to go on. But is it a good way? Consider the code If txtUserName.Text = "" Then txtUserName.SetFocus Problem: some object gets focus and you cannot have allow both objects to be tested using the LostFocus event.

Calling Event Procedures An event procedure is a subprocedure that reacts to a specific event such as a button click. You can call any given event procedure from multiple locations, as long as the procedure is in the same form or is public Example: Call cmdCalculate_Click Suffix is event, prefix is object name The word call is optional. You can call an event procedure (or any procedure for that matter) by simply using its name.

Hands on Programming Example

Debug projects by setting code breakpoints Debugging VB Projects Debug projects by setting code breakpoints Run the project, Step through the code window at break time by pressing F8, Point to variables above executed code lines to view their current values (see program shot in Notes portion of this slide) breakpoint value of variable

You can choose "Step into" or "Step over" Debugging continued You can choose "Step into" or "Step over" Step into traces all code execution, including traversing down into subprocedures Step over stays with current subprocedure only, not showing any called routines' code