Chapter 3 Variables Constants and Calculations REV 01

Chapter 3: Variables, Constants, and Calculations REV 01 Objectives • • • • Distinguish between variables, constants, and controls. Differentiate among the various data types. Apply naming conventions and indicating the data type. Declare variables and constants. Select the appropriate scope for a variable. Convert text input to numeric values. Perform calculations using variables and constants. Convert between numeric data types using implicit and explicit conversions. Round decimal values using the Decimal. Round method. Format values for output using the To. String method. Use Try/Catch blocks for error handling. Display message boxes with error messages. Accumulate sums and generate counts. DDC 3363 Programming III 1

REV 01 Chapter 3: Data - Variables & Constants Variable • Memory locations that hold data that can be changed during project execution • Example: customer’s name • Named Constant • Memory locations that hold data that cannot be changed during project execution • Example: sales tax rate DDC 3363 Programming III 2

REV 01 Chapter 3: Data - Variables & Constants • In Visual Basic, when you declare a Variable or Named Constant • An area of memory is reserved • A name is assigned called an Identifier • Follow rules and naming conventions • Use Declaration Statements to establish Variables and Constants, • Assign name and data type, • Not executable unless initialized on same line DDC 3363 Programming III 3

REV 01 Chapter 3: Data Types Data Type Use For Storage Size in bytes Boolean True or False value 2 Byte 0 to 255, binary data 1 Clear Single Unicode character 2 Date 1/1/0001 through 12/31/9999 8 Decimal fractions, such as dollars/cents 16 Single precision floating-point numbers with six digits of accuracy 4 Double precision floating-point numbers with 14 digits of accuracy 8 Short Small integer in the range -32, 768 to 32, 767 2 Integer Whole numbers in the range -2, 147, 483, 648 to +2, 147, 483, 647 4 Long Larger whole numbers 8 String Alphanumeric data: letters, digits, and other characters Varies Object Any type of data 4 DDC 3363 Programming III 4

REV 01 Chapter 3: Naming Variables and Constants • Must follow Visual Basic Naming Rules • Should follow Naming Conventions • Meaningful names consisting of letters, digits, and underscores; must begin with a letter and no spaces or periods. Include class (data type) of variable (QUOTA_Integer) • Use mixed case for variables and uppercase for constants (quantity. Integer). • Cannot use reserved words or keywords to which Basic has assigned a meaning, such as print, name, and value DDC 3363 Programming III 5

REV 01 Chapter 3: Constants • Named • User assigned name, data type, and value • Use CONST keyword to declare. Const COMPANY_ADDRESS_String As String = "101 S. Main Street" Const SALES_TAX_RATE_Decimal As Decimal =. 08 D • Intrinsic • System defined within Visual Studio DDC 3363 Programming III 6

REV 01 Chapter 3: Assigning Values to Constants • Declare the data type of numeric constants by appending a type-declaration character. Decimal D Decimal – 850. 50 D Double R Double – 52875. 8 R Integer I Long L Long – 134257987 L Short S Single F Single – 101. 25 F DDC 3363 Integer – 12345678 I Programming III 7

REV 01 Chapter 3: Declaring Variables • Declared inside a procedure using a Dim statement • Declared outside a procedure using Public, Private, • • • or Dim statements Always declare the variable’s data type. May declare several variables with one statement. Use Intelli. Sense to assist in writing statements. DDC 3363 Programming III 8

REV 01 Chapter 3: Declaration Statement Examples Dim customer. Name. String As String Private total. Sold. Integer As Integer Dim temperature. Single As Single Dim price. Decimal As Decimal Private price. Decimal As Decimal DDC 3363 Programming III 9

REV 01 Chapter 3: Scope and Lifetime of Variables • Visibility of a variable is its scope. • Scope may be • Namespace • Module level • Local • Block level • Lifetime of a variable is the period of time the variable exists. DDC 3363 Programming III 10

REV 01 Chapter 3: Module Level Variable Declaration Example Code module-level declarations in the Declaration section at the top of the code. DDC 3363 Programming III 11

REV 01 Chapter 3: Calculations • Calculations can be performed with variables, • • constants, properties of certain objects, 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 before performing a calculation DDC 3363 Programming III 12

REV 01 Chapter 3: Converting Strings to a Numeric Data Type • Use Parse methods to convert • • • the Text property to its numeric form before it’s used in a calculation. Each numeric data type class has a Parse method returns a value that can be used in calculations. Parse method fails if user enters nonnumeric data or leaves data blank. DDC 3363 Programming III 13

REV 01 Chapter 3: Converting to String • Values assigned to string variables or Text • properties must be string. Convert any numeric data type to string using. To. String method. Examples: Result. Text. Box. Text = Result. Decimal. To. String() Count. Text. Box. Text = Count. Integer. To. String() IDString = IDInteger. To. String() DDC 3363 Programming III 14

REV 01 Chapter 3: Conversion Methods Method Integer. Parse Decimal. Parse. To. String DDC 3363 Convert To Integer Decimal String Programming III 15

REV 01 Chapter 3: Conversion Examples Quantity. Integer =Integer. Parse(quantity. Text. Box. Text) Price. Decimal =Decimal. Parse(price. Text. Box. Text) Whole. Number. Integer =Integer. Parse(digit. String) Result. Text. Box. Text =Result. Decimal. To. String( ) Count. Text. Box. Text =Count. Integer. To. String( ) IDString =IDInteger. To. String( ) DDC 3363 Programming III 16

REV 01 Chapter 3: Arithmetic Operations Operator + – * / Mod ^ Operation Addition Subtraction Multiplication Division Integer Division Modulus – Remainder of division Exponentiation DDC 3363 Programming III 17

REV 01 Chapter 3: Order of Operations • Hierarchy of operations, or order of precedence, in arithmetic expressions from highest to lowest 1. Any operation inside parentheses 2. Exponentiation 3. Multiplication and division 4. Integer division 5. Modulus 6. Addition and subtraction DDC 3363 Programming III 18

REV 01 Chapter 3: Evaluation of Expression 1. All operations within parentheses. 2. All exponentiation. Multiple exponentiation operations are performed from left to right. 3. All multiplication and division. Multiple operations are performed from left to right. 4. All integer division. Multiple operations are performed from left to right. 5. Mod operations. Multiple operations are performed from left to right. 6. All addition and subtraction are performed from left to right. DDC 3363 Programming III 19

REV 01 Chapter 3: Mathematical Examples • Note the use of parentheses to control order of precedence. 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 DDC 3363 Programming III 20

REV 01 Chapter 3: Using Calculations in Code • Perform calculations in assignment statements. • What appears on right side of assignment operator is assigned to item on left side. • Assignment operators — allows shorter versions of code =, +=, -=, *=, /=, =, &= ‘Accumulate a total. Total. Sales. Decimal += sales. Decimal DDC 3363 Programming III 21

REV 01 Chapter 3: Option Explicit and Option Strict • Option Explicit forces variables to be declared • before using. Option Strict • Makes VB a strongly typed language like C++, Java and C# • Does not allow implicit conversions from a wider data type to a narrower one or between String and numeric data types • Best practice to always turn on either in code or in Project Properties dialog box DDC 3363 Programming III 22

REV 01 Chapter 3: Converting Between Numeric Data Types • Implicit (automatic) conversion • Converts value from narrower data type to wider type where no danger of losing precision exists • Explicit conversion (casting) • Uses methods of Convert class to convert between data types • Convert Class has methods that begin with “To” for each of the data types. DDC 3363 Programming III 23

REV 01 Chapter 3: Performing Calculations with Unlike Data Types • VB performs the calculations using the wider data type. • Use a cast if converting the result to a different data type. Eg: Convert. To. Int 32(Count. Integer / Number. Decimal) or Convert. To. Single(Count. Integer / Number. Decimal). • VB does not convert to a different data type until it is necessary. DDC 3363 Programming III 24

REV 01 Chapter 3: Rounding Numbers • Round decimal fractions • Decimal. Round method returns a decimal result rounded to a specified number of decimal positions. • Decimal. Round and Convert methods use technique called “rounding toward even. ” Decimal Value to Round Number of Decimal Positions Results 1, 455 2 1. 46 1, 455 2 1. 44 1. 5 0 2 2. 5 0 2 DDC 3363 Programming III 25

REV 01 Chapter 3: Formatting Data for Display • To display numeric data in a label or text box, first convert value to string. • Use To. String method Display. Text. Box. Text = Number. Integer. To. String() • Format the data using formatting codes. • Specifies use of dollar sign, percent sign, and commas • Specifies number of digits that appear to right of decimal point DDC 3363 Programming III 26

REV 01 Chapter 3: Using Format Specifier Codes • "C" code • Currency — String formatted with dollar sign, commas separating each group of 3 digits and 2 digits to the right of decimal point • "N" code • Number — String formatted with commas separating each group of 3 digits and 2 digits to the right of decimal point • Can specify number of decimal positions • Example: "C 0" zero digits DDC 3363 Programming III 27

REV 01 Chapter 3: Format Specifier Codes Name C or c Currency F or f Fixed-point N or n Number D or d Digits P or p Percent DDC 3363 Programming III 28

REV 01 Chapter 3: Format Specifier Code Examples Variable total. Decimal pin. Integer rate. Decimal value. Integer Value 1125. 6744 123 0. 075 -10 DDC 3363 Code "C" "N 0" "D 6" "P 3" "P 0" "C" Programming III Output $1, 125. 67 1, 126 000123 7. 50% 7. 500% 8% ($10. 00) 29

REV 01 Chapter 3: Date Specifier Code • Format Date. Time values using format codes • and To. String method. Date codes are case sensitive. DDC 3363 Programming III 30

REV 01 Chapter 3: Handling Exceptions • Use structured exception handling to easily catch • • • errors before run-time error occurs. Catching exceptions is referred to as error trapping. Coding to handle exception is called error handling. Error handling in Visual Studio. NET is standardized for all languages using the Common Language Runtime, CLR, which improves on previous versions of VB. DDC 3363 Programming III 31

REV 01 Chapter 3: Try/Catch Blocks • Enclose statements that might cause an error within Try/Catch block. • If an exception occurs while statements in the Try block are executing, program control is transferred to the Catch Block. • If a Finally statement is included, the code in that section executes last, whether or not an exception occurred. DDC 3363 Programming III 32

REV 01 Chapter 3: Try Block - General Form Try ‘statements that may cause an error Catch [Variable. Name As Exception. Type] ‘statements for action when an exception occurs [Finally ‘statements that always execute before exit of the Try block] End Try DDC 3363 Programming III 33

REV 01 Chapter 3: Try Block - Example Catches Any Exception Try Quantity. Integer = Integer. Parse(Quantity. Text. Box. Text) Quantity. Text. Box. Text = Quantity. Integer. To. String( ) Catch Message. Label. Text = "Error in input data. " End Try DDC 3363 Programming III 34

REV 01 Chapter 3: Try Block - Example Catches Specific Exception • This Catch statement catches bad input data that cannot be converted to numeric. Catch the. Exception As Format. Exception Message. Label. Text="Error in input data. " End Try DDC 3363 Programming III 35

REV 01 Chapter 3: Common Exception Classes Each exception is an instance of the Exception class. The properties of this class allow you to determine the code location of the error, the type of error, and cause. DDC 3363 Programming III 36

REV 01 Chapter 3: Try Block - Example Handling Multiple Exceptions Catch The. Exception As Format. Exception ' Statements for nonnumeric data. Catch The. Exception As Arithmetic. Exception ' Statements for calculation problem. Catch The. Exception As Exception ' Statements for any other exception. DDC 3363 Programming III 37

REV 01 Chapter 3: Message. Box Object • The Message. Box is an overloaded method. • Signatures correspond to the argument list. • There are multiple signatures to choose from. • Do not reverse, transpose, or leave out any of the arguments. • Intelli. Sense displays argument list (also called signatures). Message. Box. Show (Text. Message, Titlebar. Text, _ Message. Box. Buttons, Messsage. Box. Icon) DDC 3363 Programming III 38

REV 01 Chapter 3: Message. Box Object • Text. Message string • String literal or variable that displays message • Title Bar text • String that appears in title bar of message box • Message. Box Buttons • OK, OKCancel, Retry. Cancel, Yes. No. Cancel, Abort. Retry. Ignore • Message. Box Icons • Asterisk, Error, Exclamation, Hand, Information, None, Question, Stop, Warning DDC 3363 Programming III 39

REV 01 Chapter 3: Using Overloaded Methods • This OOP feature allows the Show method to act • • • differently for different arguments. Each argument list is called a signature so the Show method has several signatures. Supplied arguments must exactly match one of the signatures provided by the method. Intelli. Sense in Visual Studio editor helps when entering arguments so that they don’t need to be memorized. DDC 3363 Programming III 40

REV 01 Chapter 3: Testing Multiple Fields • Each input field presents an opportunity for an • • exception. To indicate specific fields that caused the exception, use nested Try/Catch blocks. Pinpoints specific errors, and after error, sets focus back to field in error • Use Select. All method of text box to make text appear selected to aid user. DDC 3363 Programming III 41

REV 01 Chapter 3: Counting & Accumulating Sums • • Declare module-level variables, since local level variables reset to 0 each time the procedure is called. Summing Numbers Discounted. Price. Sum. Decimal += Discounted. Price. Decimal • Counting Private sale. Count. Integer As Integer sale. Count. Integer += 1 • Calculating an Average. Discounted. Sale. Decimal = Discounted. Price. Sum. Decimal / Sale. Count. Integer DDC 3363 Programming III 42
- Slides: 42