Chapter 3 Variables Constants and Calculations Programming In
Chapter 3 Variables, Constants, and Calculations Programming In Visual Basic. NET © 2001 by The Mc. Graw-Hill Companies, Inc. All rights reserved.
Main calculation stages § Declare variables and constants § Input user entries into the variables – Read user text entries – Convert them to numeric values – Assign them to the appropriate variables § Conduct calculations (and handle exceptions) § Format the results § Display the results 2 © 2001 by The Mc. Graw-Hill Companies, Inc. All rights reserved.
Variables & Constants § Variable – Memory locations that hold data that can be changed during project execution – Ex: hours worked § Named Constant – Memory locations that hold data that cannot be changed during project execution – Ex: Sales tax percentage 3 © 2001 by The Mc. Graw-Hill Companies, Inc. All rights reserved.
Constants § Named – User defined § Intrinsic – System defined within Visual Studio – In Chapter 2 we used the Intrinsic Color Constants (e. g. Color. Green) 4 © 2001 by The Mc. Graw-Hill Companies, Inc. All rights reserved.
Data Types § § § § 5 Boolean Byte (0 to 255) Char 1/1/0001 Date From To 12/31/9999 String Decimal Object § Short (-32, 768 to 32, 767) § Integer (-2, 147, 483, 648 to 2, 147, 483, 647) § Long (larger whole numbers) § Single (floating point accuracy to 6 digits) § Double (floating point accuracy to 14 digits) © 2001 by The Mc. Graw-Hill Companies, Inc. All rights reserved.
Data Types – Prefixes § § § § 6 Boolean – bln Byte – byt Char – chr Date – dat String – str Decimal – dec Object – depends on type of object § § § Short – sht Integer – int Long – lng Single – sng Double – dbl © 2001 by The Mc. Graw-Hill Companies, Inc. All rights reserved.
Data Types – Memory Usage § § § § 7 Boolean – 2 bytes --b Byte – 1 byte Char – 2 bytes Date – 8 bytes String – varies Decimal – 16 bytes Object – 4 bytes § § § Short – 2 bytes Integer – 4 bytes Long – 8 bytes Single – 4 bytes Double – 8 bytes © 2001 by The Mc. Graw-Hill Companies, Inc. All rights reserved.
Declaration § Variables and Named Constants must be declared before being used in code § When you declare a Variable or Named Constant VB – Reserves an area of memory – Assigns it a name called an Identifier – Assigns a default value § Declaration statements are coded either – At the beginning of a procedure – In general declarations of a module 8 © 2001 by The Mc. Graw-Hill Companies, Inc. All rights reserved.
Declaration Statements § DIM used to declare Variables § CONST used to declare Named Constants § Declaration includes – Name, follow Naming Convention Rules – Data Type – Required Value for Constants – Optional Initial Value for Variables 9 © 2001 by The Mc. Graw-Hill Companies, Inc. All rights reserved.
Declaration Examples Dim str. Name, str. SSN Dim int. Age Dim dec. Pay. Rate Dim dat. Hire. Date Dim bln. Insured Dim lng. Population As String As Short As Decimal = 8. 25 As Date As Boolean As Long Const dec. DISCOUNT_RATE As Decimal =. 15 Note: Constants are named using all uppercase letters EXCEPT the prefix. 10 © 2001 by The Mc. Graw-Hill Companies, Inc. All rights reserved.
Type-Declaration Characters § Append single character to the end of the Constant's Value to indicate the Data Type § Short – S § Integer – I § Long – L 11 § Decimal – D § Single – F § Double – R © 2001 by The Mc. Graw-Hill Companies, Inc. All rights reserved.
Variables – Scope & Lifetime § Global/Public (use sparingly and cautiously) – Available to all modules and procedures of Project – Initialized at start of Project § Module/Private (Form) – Available to one module and all procedures within that module – Initialized 1 st time the Form is loaded § Local – Available only to the procedure it is declared in – Initialized every time the Procedure runs § Block (not used until later in this course) – Available only to the block of code inside a procedure it is declared in – Initialized every time the Procedure runs 12 © 2001 by The Mc. Graw-Hill Companies, Inc. All rights reserved.
Scope Declaring & Naming § Global/Public g prefix – Declare in General Declarations as Public • Dim gstr. Name as String § Module/Private m prefix – Declare in Module’s General Declarations as Private • Dim mstr. Name as String § Local no prefix required – Declare in Event Procedures • Dim str. Name as String 13 © 2001 by The Mc. Graw-Hill Companies, Inc. All rights reserved.
Declaring Module Level Variables Example 14 © 2001 by The Mc. Graw-Hill Companies, Inc. All rights reserved.
Calculations § Calculations can be performed using properties of certain objects, variables, constants, and numeric literals § Do Not use Strings in calculations § Values from Text property of Text Boxes – Are Strings, even if they contain numeric data – Must be converted to a Numeric Data Type 15 © 2001 by The Mc. Graw-Hill Companies, Inc. All rights reserved.
Numeric Conversion Functions § Functions perform an action and return a value § Expression to operate on is called the Argument § Conversion Functions convert arguments into a numeric value of the correct data type § Conversion Functions on Text Boxes fail if user enters nonnumeric data or leaves the Text Box blank 16 © 2001 by The Mc. Graw-Hill Companies, Inc. All rights reserved.
Conversion Functions (cont. ) Function CInt ** CDec CStr Convert To Integer Decimal String ** CInt rounds to the nearest Even Number 17 © 2001 by The Mc. Graw-Hill Companies, Inc. All rights reserved.
Conversion Examples int. Quantity dec. Price int. Whole. Number dec. Dollars str. Value = = = CInt(txt. Quantity. Text) CDec(txt. Price. Text) CInt(dec. Fractional. Value) CDec(int. Dollars) CStr(dec. Value) Function Name 18 Argument To Be Acted Upon © 2001 by The Mc. Graw-Hill Companies, Inc. All rights reserved.
Mathematical Operators Operator + – * / Mod ^ 19 Operation Addition Subtraction Multiplication Division Integer Division Modulus (division's remainder) Exponentiation © 2001 by The Mc. Graw-Hill Companies, Inc. All rights reserved.
Mathematical Order of Operations § Computers solve math formulas based on a specific order 1 st, then left to right 1. 2. 3. 4. 5. 6. 20 Parentheses Exponentiation Multiplication & Division Integer Division Modulus Addition & Subtraction © 2001 by The Mc. Graw-Hill Companies, Inc. All rights reserved.
Mathematical Examples § Note the use of parentheses to control 3+4*2 = 11 Multiply then add (3+4)*2 = 14 Parentheses control: add then multiply 8/4*2 = 4 Same level, left to right: divide then multiply 21 © 2001 by The Mc. Graw-Hill Companies, Inc. All rights reserved.
Option Explicit § On by default - should be left on § If turned off – Variables can be used without first being declared – They will be defined by VB as data type Object § To turn off – Code Option Explicit Off or Option Explicit in General Declarations – Set in Project Properties dialog box 22 © 2001 by The Mc. Graw-Hill Companies, Inc. All rights reserved.
Option Strict § Off by default - should be turned on § If turned on – VB becomes strongly typed language – Will not allow implicit conversions from a wider data type to a narrower one or between String and numeric data types § To turn on – Code Option Strict On in General Declarations – Set in Project Properties dialog box 23 © 2001 by The Mc. Graw-Hill Companies, Inc. All rights reserved.
Format. Currency Function § General Form – Format. Currency(Numeric. Expression) § Returns a string of characters formatted as dollars and cents § Includes a Dollar Sign, commas, and 2 decimal places by default § Value returned is a String and can no longer be used in calculations 24 © 2001 by The Mc. Graw-Hill Companies, Inc. All rights reserved.
Format. Number Function § General Form – Format. Number(Numeric. Expression [ , Decimal Places [ , Leading Digit [ , Use Parentheses for Negative Numbers [ , Grouping for Digits] ] ) § Formats with commas and specified number of decimal places (2 by default) Line Continuation not included on this slide 25 © 2001 by The Mc. Graw-Hill Companies, Inc. All rights reserved.
Format. Percent Function § General Form – Format. Percent(Numeric. Expression [, Decimal Places[, Leading Digit [, Use Parentheses for Negative Numbers [, Grouping for Digits ] ] ) § Returns a string of characters formatted as a percent § Multiplies the argument by 100, adds a percent sign and rounds to 2 decimal places by default Line Continuation not included on this slide 26 © 2001 by The Mc. Graw-Hill Companies, Inc. All rights reserved.
Format. Date. Time Function § General Form – Format. Date. Time(Expression [, Named Format] ) § Expression can be: – String that holds a date or time – Date type variable 27 © 2001 by The Mc. Graw-Hill Companies, Inc. All rights reserved.
Named Formats Format. Date. Time Function Named Format Date. Format. General. Date. Format. Short. Date. Format. Long. Date. Format. Short. Time Date. Format. Long. Time 28 Example 2/28/99 6: 01: 24 PM 2/28/99 Sunday, February 28, 1999 18: 01(24 Hour Clock) 6: 01: 24 PM © 2001 by The Mc. Graw-Hill Companies, Inc. All rights reserved.
Handling Exceptions § Exceptions occur when user enters unexpected/invalid data and program code does not anticipate this possibility, such as – User enters nonnumeric data in Text Box and code attempts to run a Numeric Conversion Function – User enters data that results in division by zero 29 © 2001 by The Mc. Graw-Hill Companies, Inc. All rights reserved.
Try/Catch Blocks § Used to catch and handle exceptions; referred to as error trapping or handling § Enclose statements that might cause an error within Try/Catch Block – If an error occurs control is transferred to the Catch Block – Include a Finally statement to indicate code that should execute last whether or not an exception occurred 30 © 2001 by The Mc. Graw-Hill Companies, Inc. All rights reserved.
Try Block - General Form Try statements that may cause error Catch [Variable. Name as Exception. Type] statements for action when an exception occurs [Finally statements that always execute before exit of Try block] End Try See p 111 for list of common Exception Classes 31 © 2001 by The Mc. Graw-Hill Companies, Inc. All rights reserved.
Try Block - Example 1 Catches All Exceptions Try int. Quantity=CInt(txt. Quantity. Text) lbl. Quantity. Text=CStr(int. Quantity) Catch lbl. Message. Text="Error in input data. " End Try 32 © 2001 by The Mc. Graw-Hill Companies, Inc. All rights reserved.
Try Block - Example 2 Catches Specific Exception Try int. Quantity=CInt(txt. Quantity. Text) lbl. Quantity. Text=CStr(int. Quantity) Catch My. Err as Invalid. Cast. Exception lbl. Message. Text="Error in input data. " End Try Conversion exception, usually caused by nonnumeric or blank data 33 © 2001 by The Mc. Graw-Hill Companies, Inc. All rights reserved.
Try Block - Example 3 Catches Multiple Specific Exceptions Try statements that may cause errors Catch My. Err as Invalid. Cast. Exception error messages and statements for nonnumeric data Catch My. Err as Arithmetic. Exception error messages and statements for calculation problems Catch My. Err as Exception error messages and statements for any other exception End Try 34 © 2001 by The Mc. Graw-Hill Companies, Inc. All rights reserved.
Message. Box Object § Use Show Method of Message. Box to display special type of window § Arguments of Show method – Message to display – Optional Title Bar Caption – Optional Button(s) – Optional Icon 35 © 2001 by The Mc. Graw-Hill Companies, Inc. All rights reserved.
Message. Box Syntax § The Message. Box is an Overloaded Method – Signatures correspond to the Argument list – There are multiple Signatures to choose from – Arguments must be included to exactly match one of the predefined Signatures Message. Box. Show (Text. Message, Titlebar. Text, _ Message. Box. Buttons, Messsage. Box. Icon) 36 © 2001 by The Mc. Graw-Hill Companies, Inc. All rights reserved.
Message. Box. Buttons Constants § § § 37 OK OKCancel Retry. Cancel Yes. No. Cancel Abort. Retry. Ignore © 2001 by The Mc. Graw-Hill Companies, Inc. All rights reserved.
Message. Box. Icon Constants § § § 38 Asterisk Error Exclamation Hand Information § § None Question Stop Warning © 2001 by The Mc. Graw-Hill Companies, Inc. All rights reserved.
Counting & Accumulating Sums § Must use Module/Form level variables since Local/Event level variables reset to 0 each time the procedure is called § Summing – mdec. Order. Total = mdec. Order. Total + dec. Item. Price § Counting – mint. Num. Items = mint. Num. Items + 1 – mint. Num. Items += mint. Num. Items § Averaging – mdec. Ave. Sale = mdec. Order. Total / mint. Num. Items 39 © 2001 by The Mc. Graw-Hill Companies, Inc. All rights reserved.
- Slides: 39