Variables, Constants and Calculations

You might also like

Download as ppt, pdf, or txt
Download as ppt, pdf, or txt
You are on page 1of 41

Chapter 3

Variables, Constants
and Calculations

Programming In
Visual Basic .NET
Data - Variables and 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

3- 2 © 2005 by The McGraw-Hill Companies, Inc. All rights reserved.


Data - Variables and Constants
(continued)

• 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

3- 3 © 2005 by The McGraw-Hill Companies, Inc. All rights reserved.


Data Types (p 87 Table 3.1)

• Boolean • Short (-32,768 to 32,767)


• Byte (0 to 255) • Integer (-2,147,483,648 to
• Char 2,147,483,647)
• Date • Long (larger whole numbers)
• String • Single (floating point accuracy to 6
• digits)
Decimal
• • Double (floating point accuracy to 14
Object
digits)

3- 4 © 2005 by The McGraw-Hill Companies, Inc. All rights reserved.


Data Types – Memory Usage

• Boolean – 2 bytes • Short – 2 bytes


• Byte – 1 byte • Integer – 4 bytes
• Char – 2 bytes • Long – 8 bytes
• Date – 8 bytes • Single – 4 bytes
• String – varies • Double – 8 bytes
• Decimal – 16 bytes
• Object – 4 bytes

3- 5 © 2005 by The McGraw-Hill Companies, Inc. All rights reserved.


Naming Variables and Constants

• Must follow Visual Basic Naming Rules


• Should follow Naming Conventions
– Meaningful names
– Include class (data type) of variable
– Use mixed case for variables and uppercase for
constants

3- 6 © 2005 by The McGraw-Hill Companies, Inc. All rights reserved.


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 = .08D
• Intrinsic
– System defined within Visual Studio
– In Chapter 2 we used the Intrinsic Color Constants

3- 7 © 2005 by The McGraw-Hill Companies, Inc. All rights reserved.


Assigning Values to Constants

• Declare the data type of numeric constants by appending a


type-declaration character

• Decimal - D • Long - L
• Double - R • Short - S
• Integer - I • Single - F

Integer – 12345678I Single – 101.25F


Decimal – 850.50D Double – 52875.8R
Long – 134257987L

3- 8 © 2005 by The McGraw-Hill Companies, Inc. All rights reserved.


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 IntelliSense to assist in writing statements

3- 9 © 2005 by The McGraw-Hill Companies, Inc. All rights reserved.


Declaration Examples

Dim customerNameString As String


Private totalSoldInteger As Integer
Dim temperatureSingle As Single
Dim priceDecimal As Decimal
Private priceDecimal As Decimal

3- 10 © 2005 by The McGraw-Hill Companies, Inc. All rights reserved.


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

3- 11 © 2005 by The McGraw-Hill Companies, Inc. All rights reserved.


Scope and Lifetime of Variables
(continued)
• Namespace
– Available to all procedures of project
– Good programming practice excludes use of Namespace
variables
• Module
– Available to all procedures within that module (often a form)
– Use Public or Private keywords
– Place in declaration section of module (form)
• Local
– Available only to the procedure it is declared in
– Declare with Dim keyword and place at top of procedure
• Block (not used until later in this course)
– Available only in block of code where declared

3- 12 © 2005 by The McGraw-Hill Companies, Inc. All rights reserved.


Module Level Variable Declaration
Example

3- 13 © 2005 by The McGraw-Hill Companies, Inc. All rights reserved.


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

3- 14 © 2005 by The McGraw-Hill Companies, Inc. All rights reserved.


Converting Strings to a
Numeric Data Type

• Use Parse methods to convert Text to numeric data


• Each numeric data type class has a Parse method
• Parse method returns a value that can be used in
calculations
• Parse method fails if user enters nonnumeric data or leaves
data blank

3- 15 © 2005 by The McGraw-Hill Companies, Inc. All rights reserved.


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- 16 © 2005 by The McGraw-Hill Companies, Inc. All rights reserved.


Conversion Methods

Method Convert
To
Integer.Parse Integer
Decimal.Parse Decimal
.ToString String

3- 17 © 2005 by The McGraw-Hill Companies, Inc. All rights reserved.


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- 18 © 2005 by The McGraw-Hill Companies, Inc. All rights reserved.


Arithmetic Operations

Operator Operation
+ Addition
– Subtraction
* Multiplication
/ Division
\ Integer Division
Mod Modulus – Remainder of
division
^ Exponentiation
3- 19 © 2005 by The McGraw-Hill Companies, Inc. All rights reserved.
Order of Operations

• 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

3- 20 © 2005 by The McGraw-Hill Companies, Inc. All rights reserved.


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

3- 21 © 2005 by The McGraw-Hill Companies, Inc. All rights reserved.


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
=, +=, -=, *=, /=, \=, &=

3- 22 © 2005 by The McGraw-Hill Companies, Inc. All rights reserved.


Option Explicit and Option Strict

• Option Explicit forces variables to be declared before using


• Option Strict
– Makes VB a strongly typed language
– 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- 23 © 2005 by The McGraw-Hill Companies, Inc. All rights reserved.


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
• ToDecimal, ToSingle, ToDouble, ToInt16 (Short),
ToInt32 (Integer), ToInt64 (Long)

3- 24 © 2005 by The McGraw-Hill Companies, Inc. All rights reserved.


Rounding Numbers

• Round decimal fractions


– Use Decimal.Round method
– Decimal.Round and Convert methods use technique
called “rounding toward even”
• See Appendix B for additional mathematical, financial and
string functions

3- 25 © 2005 by The McGraw-Hill Companies, Inc. All rights reserved.


Formatting Data for Display
• To display numeric data in a label or text box, first convert
value to string
– Use ToString method
resultLabel.Text = resultDecimal.ToString( )
countTextBox.Text = countInteger.ToString( )
• 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

3- 26 © 2005 by The McGraw-Hill Companies, Inc. All rights reserved.


Using Format Specifier Codes
• "C" code
– Currency – String formatted with dollar sign, commas
separating each group of three digits and two digits to
the right of decimal point
• "N" code
– Number – String formatted with commas separating
each group of three digits and two digits to the right of
decimal point
• Can specify number of decimal positions
– Example: "C0" zero digits

3- 27 © 2005 by The McGraw-Hill Companies, Inc. All rights reserved.


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- 28 © 2005 by The McGraw-Hill Companies, Inc. All rights reserved.


Format Specifier Codes 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- 29 © 2005 by The McGraw-Hill Companies, Inc. All rights reserved.


Date Specifier Code

• Format DateTime values using format codes and ToString


method
• Date codes are case sensitive
d Short date D Long date
t Short time T Long time
f Full date/time F Full
date/time
g General (short time) G General
(long time)
M or m Month R or r GMT pattern
• ToLongDateString, ToShortDateString, ToLongTimeString,
ToShortTimeString methods also available

3- 30 © 2005 by The McGraw-Hill Companies, Inc. All rights reserved.


Handling Exceptions

• Use structured exception handling to catch errors before


run-time error occurs
• Catching exceptions referred to as error trapping
• Code to handle exception called error handling
• Error handling in Visual Studio .NET is standardized for
all languages using the CLR

3- 31 © 2005 by The McGraw-Hill Companies, Inc. All rights reserved.


Try/Catch Blocks

• Enclose statements that might cause an error within


Try/Catch block
– If an error occurs 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- 32 © 2005 by The McGraw-Hill Companies, Inc. All rights reserved.


Try Block - General Form

Try
statements that may cause error
Catch [VariableName As ExceptionType]
statements for action when an exception occurs
[Finally
statements that always execute before exit of Try block]
End Try

See page 114 for list of common Exception Classes

3- 33 © 2005 by The McGraw-Hill Companies, Inc. All rights reserved.


Try Block - Example
Catches Any Exception

Try
quantityInteger = Integer.Parse(quantityTextBox.Text)
quantityLabel.Text = quantityInteger.ToString( )
Catch
messageLabel.Text = "Error in input data."
End Try

3- 34 © 2005 by The McGraw-Hill Companies, Inc. All rights reserved.


Try Block - Example
Catches Specific Exception

Try
quantityInteger = Integer.Parse(quantityTextBox.Text)
quantityLabel.Text = quantityInteger.ToString( )
Catch theException As FormatException
messageLabel.Text="Error in input data."
End Try

Failure of numeric conversion, usually


blank or nonnumeric data

3- 35 © 2005 by The McGraw-Hill Companies, Inc. All rights reserved.


Try Block - Example
Handling 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- 36 © 2005 by The McGraw-Hill Companies, Inc. All rights reserved.


Displaying Messages in Message
Boxes

• Use Show method of MessageBox to display message box,


a special type of window
• Arguments of Show method
– Message to display
– Optional Title Bar Caption
– Optional Button(s)
– Optional Icon

3- 37 © 2005 by The McGraw-Hill Companies, Inc. All rights reserved.


MessageBox Object

• The MessageBox 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
– IntelliSense displays argument list (also called
signatures)

MessageBox.Show (TextMessage, TitlebarText, _


MessageBoxButtons, MesssageBoxIcon)

3- 38 © 2005 by The McGraw-Hill Companies, Inc. All rights reserved.


MessageBox Object (continued)

• TextMessage string
– String literal or variable that displays message
• Title Bar text
– String that appears in title bar of message box
• MessageBox Buttons
– OK, OKCancel, RetryCancel, YesNo, YesNoCancel,
AbortRetryIgnore
• MessageBox Icons
– Asterisk, Error, Exclamation, Hand, Information, None,
Question, Stop, Warning

3- 39 © 2005 by The McGraw-Hill Companies, Inc. All rights reserved.


Testing Multiple Fields

• Each input field presents a chance for an error


• To indicate specific field that caused error use nested
Try/Catch blocks
• After error set focus back to field in error
– Use SelectAll method of text box to make text appear
selected to aid user

3- 40 © 2005 by The McGraw-Hill Companies, Inc. All rights reserved.


Counting and Accumulating Sums

• Declare module-level variables, since local level variables


reset to 0 each time the procedure is called
• Summing Numbers
discountedPriceSumDecimal += discountedPriceDecimal
• Counting

Private saleCountInteger As Integer


saleCountInteger += 1

• Calculating an Average
averageDiscountedSaleDecimal = discountedPriceSumDecimal / saleCountInteger

3- 41 © 2005 by The McGraw-Hill Companies, Inc. All rights reserved.

You might also like