Post on 25-May-2015
3-1
aslkjdhfalskhjfgalsdkfhalskdhjfglaskdhjflaskdhjfglaksjdhflakshflaksdhjfglaksjhflaksjhfaslkjdhfalskhjfgalsdkfhalskdhjfglaskdhjflaskdhjfglaksjdhflakshflaksdhjfglaksjhflaksjhfaslkjdhfalskhjfgalsdkfhalskdhjfglaskdhjflaskdhjfglaksjdhflakshflaksdhjfglaksjhflaksjhfaslkjdhfalskhjfgalsdkfhalskdhjfglaskdhjflaskdhjfglaksjdhflakshflaksdhjfglaksjhflaksjhfaslkjdhfalskhjfgalsdkfhalskdhjfglaskdhjflaskdhjfglaksjdhflakshflaksdhjfglaksjhflaksjhfaslkjdhfalskhjfgalsdkfhalskdhjfglaskdhjflaskdhjfglaksjdhflakshflaksdhjfglaksjhflaksjhfaslkjdhfalskhjfgalsdkfhalskdhjfglaskdhjflaskdhjfglaksjdhflakshflaksdhjfglaksjhflaksjhfaslkjdhfalskhjfgalsdkfhalskdhjfglaskdhjflaskdhjfglaksjdhflakshflaksdhjfglaksjhflaksjhfaslkjdhfalskhjfgalsdkfhalskdhjfglaskdhjflaskdhjfglaksjdhflakshflaksdhjfglaksjhflaksjhfaslkjdhfalskhjfgalsdkfhalskdhjfglaskdhjflaskdhjfglaksjdhflakshflaksdhjfglaksjhflaksjhfaslkjdhfalskhjfgalsdkfhalskdhjfglaskdhjflaskdhjfglaksjdhflakshflaksdhjfglaksjhflaksjhfaslkjdhfalskhjfgalsdkfhalskdhjfglaskdhjflaskdhjfglaksjdhflakshflaksdhjfglaksjhflaksjhfaslkjdhfalskhjfgalsdkfhalskdhjfglaskdhjflaskdhjfglaksjdhflakshflaksdhjfglaksjhflaksjhfaslkjdhfalskhjfgalsdkfhalskdhjfglaskdhjflaskdhjfglaksjdhflakshflaksdhjfglaksjhflaksjhfaslkjdhfalskhjfgalsdkfhalskdhjfglaskdhjflaskdhjfglaksjdhflakshflaksdhjfglaksjhflaksjhfaslkjdhfalskhjfgalsdkfhalskdhjfglaskdhjflaskdhjfglaksjdhflakshflaksdhjfglaksjhflaksjhfaslkjdhfalskhjfgalsdkfhalskdhjfglaskdhjflaskdhjfglaksjdhflakshflaksdhjfglaksjhflaksjhfaslkjdhfalskhjfgalsdkfhalskdhjfglaskdhjflaskdhjfglaksjdhflakshflaksdhjfglaksjhflaksjhfaslkjdhfalskhjfgalsdkfhalskdhjfglaskdhjflaskdhjfglaksjdhflakshflaksdhjfglaksjhflaksjhfaslkjdhfalskhjfgalsdkfhalskdhjfglaskdhjflaskdhjfglaksjdhflakshflaksdhjfglaksjhflaksjhfaslkjdhfalskhjfgalsdkfhalskdhjfglaskdhjflaskdhjfglaksjdhflakshflaksdhjfglaksjhflaksjhfaslkjdhfalskhjfgalsdkfhalskdhjfglaskdhjflaskdhjfglaksjdhflakshflaksdhjfglaksjhflaksjhfaslkjdhfalskhjfgalsdkfhalskdhjfglaskdhjflaskdhjfglaksjdhflakshflaksdhjfglaksjhflaksjhfaslkjdhfalskhjfgalsdkfhalskdhjfglaskdhjflaskdhjfglaksjdhflakshflaksdhjfglaksjhflaksjhf
Variables, Constants and Calculations
Chapter 33
McGraw-Hill © 2006 The McGraw-Hill Companies, Inc. All rights reserved.
3-3
Objectives (1 of 2)
Distinguish between variables, constants, and controlsDifferentiate among the various data typesApply naming conventions incorporating standards
and indicating the data typeDeclare variables and constantsSelect the appropriate scope for a variableConvert text input to numeric values
3-4
Objectives (2 of 2)
Perform calculations using variables and constantsConvert between numeric data types using implicit
and explicit conversionsRound decimal values using the Decimal.Round
method Format values for output using the ToString method.Use Try/Catch blocks for error handlingDisplay message boxes with error messages Accumulate sums and generate counts
3-5
Data - Variables and Constants (1 of 2)
VariableMemory locations that hold data that can be changed
during project executionExample: customer’s name
Named ConstantMemory locations that hold data that cannot be changed
during project executionExample: sales tax rate
3-6
Data - Variables and Constants (2 of 2)
In Visual Basic when you declare a Variable or Named Constant An area of memory is reservedA name is assigned called an IdentifierFollow rules and naming conventions
Use Declaration Statements to establish Variables and ConstantsAssign name and data typeNot executable unless initialized on same line
3-7
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 Decimal fractions, such as dollars/cents 16
Single Single precision floating-point numbers with six digits of accuracy
4
Double 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
3-8
Naming Variables and Constants
Must follow Visual Basic Naming RulesShould 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 (quantityInteger)
Can not use reserved words or keywords that Basic has assigned a meaning such as print, name, and value
3-9
Constants
NamedUser assigned name, data type and valueUse CONST keyword to declare
IntrinsicSystem defined within Visual Studio
Const COMPANY_ADDRESS_String As String = "101 S. Main Street"Const SALES_TAX_RATE_Decimal As Decimal = .08D
3-10
Assigning Values to Constants
Declare the data type of numeric constants by appending a type-declaration character
Decimal D Decimal – 850.50D
Double R Double – 52875.8R
Integer I Integer – 12345678I
Long L Long – 134257987L
Short S
Single F Single – 101.25F
3-11
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 typeMay declare several variables with one
statementUse IntelliSense to assist in writing statements
3-12
Declaration Statement Examples
Dim customerName Strging As String
As String
Private totalSoldInteger As Integer As Integer
Dim temperatureSingle As Single
Dim priceDecimal As Decimal
Private priceDecimal As Decimal
3-13
Scope and Lifetime of Variables (1 of 2)
Visibility of a variable is its scopeScope may be
NamespaceModule levelLocalBlock level
Lifetime of a variable is the period of time the variable exists
3-14
Module Level Variable Declaration Example
Code module-level declarations in the Declaration section at the top of the code
3-15
Calculations
Calculations can be performed with variables, constants, properties of certain objects, and numeric literals
Do not use strings in calculationsValues from Text property of Text Boxes
Are strings, even if they contain numeric dataMust be converted to a numeric data type before
performing a calculation
3-16
Converting Strings to aNumeric 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 methodParse method returns a value that can be used in
calculationsParse method fails if user enters nonnumeric data
or leaves data blank
3-17
Converting to String
Values assigned to string variables or Text properties must be string
Convert any numeric data type to string using .ToString method
3-18
Conversion Methods
Method Convert ToInteger.Parse IntegerDecimal.Parse Decimal.ToString String
3-19
Conversion Examples
quantityInteger =Integer.Parse(quantityTextBox.Text)priceDecimal =Decimal.Parse(priceTextBox.Text)wholeNumberInteger =Integer.Parse(digitString)resultLabel.Text =resultDecimal.ToString( )countTextBox.Text =countInteger.ToString( )idString =idInteger.ToString( )
3-20
Arithmetic Operations
Operator Operation+ Addition– Subtraction* Multiplication/ Division\ Integer Division
Mod Modulus – Remainder of division
^ Exponentiation
3-21
Order of Operations
Hierarchy of operations, or order of precedence, in arithmetic expressions from highest to lowest
1. Any operation inside parentheses2. Exponentiation3. Multiplication and division4. Integer division5. Modulus6. Addition and subtraction
3-22
Evaluation of Expression
1. All operations within parentheses. Multiple operations within the parentheses are performed according to the rules of precedence.
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.
3-23
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 multiply8/4*2 = 4 Same level, left to right: divide then multiply
3-24
Using Calculations in Code
Perform calculations in assignment statementsWhat appears on right side of assignment operator is
assigned to item on left sideAssignment operators – allows shorter versions of
code =, +=, -=, *=, /=, \=, &=
‘Accumulate a total.
TotalSalesDecimal += salesDecimal
3-25
Option Explicit and Option Strict
Option Explicit forces variables to be declared before using
Option StrictMakes 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
3-26
Converting Between Numeric Data Types
Implicit (automatic) conversionConverts 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
3-27
Performing Calculations with Unlike Data Types
VB performs the calculations using the wider data type
Perform a cast if converting the result to a different data type
VB does not convert to a different data type until it is necessary
3-28
Rounding Numbers
Round decimal fractionsDecimal.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
3-29
Formatting Data for Display
To display numeric data in a label or text box, first convert value to stringUse ToString method
Format the data using formatting codesSpecifies use of dollar sign, percent sign and
commasSpecifies number of digits that appear to right of
decimal point
Me.displayTextBox.Text = numberInteger.ToString()
3-30
Using Format Specifier Codes
"C" codeCurrency – String formatted with dollar sign,
commas separating each group of 3 digits and 2 digits to the right of decimal point
"N" codeNumber – String formatted with commas
separating each group of 3 digits and 2 digits to the right of decimal point
Can specify number of decimal positionsExample: "C0" zero digits
3-31
Format Specifier Codes
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
3-32
Format Specifier Code Examples
Variable Value Code Output
totalDecimal
1125.6744 "C" $1,125.67
totalDecimal
1125.6744 "N0" 1,126
pinInteger 123 "D6" 000123
rateDecimal 0.075 "P" 7.50%
rateDecimal 0.075 "P3" 7.500%
rateDecimal 0.075 "P0" 8%
valueInteger -10 "C" ($10.00)
3-33
Date Specifier Code
Format DateTime values using format codes and ToString method
Date codes are case sensitive
3-34
Handling Exceptions
Use structured exception handling to easily catch errors before run-time error occurs
Catching exceptions referred to as error trapping
Coding to handle exception 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
3-35
Try/Catch Blocks
Enclose statements that might cause an error within Try/Catch blockIf 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
3-36
Try Block - General Form
Trystatements that may cause error
Catch [VariableName As ExceptionType]statements for action when an exception occurs
[Finallystatements that always execute before exit of Try block]
End Try
3-37
Try Block - ExampleCatches Any Exception
TryquantityInteger = Integer.Parse(quantityTextBox.Text)Me.quantityLabel.Text = quantityInteger.ToString( )
CatchMe.messageLabel.Text = "Error in input data."
End Try
3-38
Try Block - ExampleCatches Specific Exception
This Catch statement catches bad input data that cannot be converted to numeric
Catch theException As FormatExceptionmessageLabel.Text="Error in input data."
End Try
3-39
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.
3-40
Try Block - ExampleHandling Multiple Exceptions
Try' Statements that may cause errors.
Catch theException As FormatException' Statements for nonnumeric data.
Catch theException As ArithmeticException' Statements for calculation problem.
Catch theException As Exception' Statements for any other exception.
End Try
3-41
MessageBox Object (1 of 2)
MessageBox.Show (TextMessage, TitlebarText, _ MessageBoxButtons, MesssageBoxIcon)
The MessageBox is an overloaded methodSignatures correspond to the argument listThere are multiple signatures to choose fromDo not reverse, transpose or leave out any of the argumentsIntelliSense displays argument list (also called signatures)
3-42
MessageBox Object (2 of 2)
TextMessage stringString literal or variable that displays message
Title Bar textString that appears in title bar of message box
MessageBox ButtonsOK, OKCancel, RetryCancel, YesNo, YesNoCancel,
AbortRetryIgnoreMessageBox Icons
Asterisk, Error, Exclamation, Hand, Information, None, Question, Stop, Warning
3-43
Using Overloaded Methods
This OOP feature allows the Show method to act differently for different arguments
Each argument list if called a signature so the Show method has several signatures
Supplied arguments must exactly match one of the signatures provided by the method
IntelliSense in Visual Studio editor helps when entering arguments so that they don’t need to be memorized
3-44
Testing Multiple Fields
Each input field presents an opportunity for an exception
To indicate specific field that caused the exception use nested Try/Catch blocks
Pinpoints specific errors and after error set focus back to field in errorUse SelectAll method of text box to make text appear
selected to aid user
3-45
Counting and Accumulating Sums
Declare module-level variables, since local level variables reset to 0 each time the procedure is called
Summing Numbers
Counting
Calculating an Average
discountedPriceSumDecimal += discountedPriceDecimal
Private saleCountInteger As IntegersaleCountInteger += 1
averageDiscountedSaleDecimal = discountedPriceSumDecimal / saleCountInteger