chapter 3 variables, constants and calculations programming in visual basic.net

38
Chapter 3 Variables, Constants and Calculations Programming In Visual Basic.NET

Upload: hannah-crawford

Post on 13-Dec-2015

221 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Chapter 3 Variables, Constants and Calculations Programming In Visual Basic.NET

Chapter 3Variables,

Constants and Calculations

Programming In

Visual Basic.NET

Page 2: Chapter 3 Variables, Constants and Calculations Programming In Visual Basic.NET

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

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

Page 3: Chapter 3 Variables, Constants and Calculations Programming In Visual Basic.NET

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

Constants

• Named– User defined

• Intrinsic– System defined within Visual Studio– In Chapter 23 we used the Intrinsic Color

Constants

Page 4: Chapter 3 Variables, Constants and Calculations Programming In Visual Basic.NET

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

Declaration

• Variables and Named Constants must bedeclared 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

• Declaration statements are coded either– Beginning of a procedure

– General Declarations of a module

Page 5: Chapter 3 Variables, Constants and Calculations Programming In Visual Basic.NET

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

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

Page 6: Chapter 3 Variables, Constants and Calculations Programming In Visual Basic.NET

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

Data Types (p 85 Table 3.1)

• Boolean• Byte (0 to 255)• Char• Date• 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 points)

Page 7: Chapter 3 Variables, Constants and Calculations Programming In Visual Basic.NET

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

Data Types – Memory Usage

• Boolean – 2 bytes• 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

Page 8: Chapter 3 Variables, Constants and Calculations Programming In Visual Basic.NET

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

Data Types – Prefixes

• 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

Page 9: Chapter 3 Variables, Constants and Calculations Programming In Visual Basic.NET

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

Dim strName, strSSN As StringDim intAge As ShortDim decPayRate As Decimal = 8.25Dim datHireDate As DateDim blnInsured As BooleanDim lngPopulation As Long

Const decDISCOUNT_RATE As Decimal = .15

Note: Constants are named using all uppercase letters EXCEPT the prefix.

Declaration Examples

Page 10: Chapter 3 Variables, Constants and Calculations Programming In Visual Basic.NET

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

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

• Decimal – D • Single – F• Double – R

Page 11: Chapter 3 Variables, Constants and Calculations Programming In Visual Basic.NET

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

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 1st 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

Page 12: Chapter 3 Variables, Constants and Calculations Programming In Visual Basic.NET

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

Scope Declaring & Naming

• Global/Public g prefix– Declare in General Declarations as Public

• Dim gstrName as String

• Module/Private m prefix– Declare in Module’s General Declarations as Private

• Dim mstrName as String

• Local no prefix required– Declare in Event Procedures

• Dim strName as String

Page 13: Chapter 3 Variables, Constants and Calculations Programming In Visual Basic.NET

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

Declaring Module Level Variables Example

Page 14: Chapter 3 Variables, Constants and Calculations Programming In Visual Basic.NET

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

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

Page 15: Chapter 3 Variables, Constants and Calculations Programming In Visual Basic.NET

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

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

Page 16: Chapter 3 Variables, Constants and Calculations Programming In Visual Basic.NET

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

Conversion Functions (cont.)

Function Convert ToCInt ** IntegerCDec DecimalCStr String

** CInt rounds to the nearest Even Number

Page 17: Chapter 3 Variables, Constants and Calculations Programming In Visual Basic.NET

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

Conversion Examples(also review examples p 96)

FunctionName

ArgumentTo Be Acted Upon

intQuantity = CInt(txtQuantity.Text)decPrice = CDec(txtPrice.Text)intWholeNumber = CInt(decFractionalValue)decDollars = CDec(intDollars)strValue = CStr(decValue)

Page 18: Chapter 3 Variables, Constants and Calculations Programming In Visual Basic.NET

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

Mathematical Operators

Operator Operation+ Addition– Subtraction* Multiplication/ Division\ Integer Division

Mod Modulus (division's remainder)

^ Exponentiation

Page 19: Chapter 3 Variables, Constants and Calculations Programming In Visual Basic.NET

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

Mathematical Order of Operations

• Computers solve math formulas based on a specific order 1st, then left to right

1. Parentheses

2. Exponentiation

3. Multiplication & Division

4. Integer Division

5. Modulus

6. Addition & Subtraction

Page 20: Chapter 3 Variables, Constants and Calculations Programming In Visual Basic.NET

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

Mathematical Examples

• Note the use of parentheses to control

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

Page 21: Chapter 3 Variables, Constants and Calculations Programming In Visual Basic.NET

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

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

Page 22: Chapter 3 Variables, Constants and Calculations Programming In Visual Basic.NET

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

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

Page 23: Chapter 3 Variables, Constants and Calculations Programming In Visual Basic.NET

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

FormatCurrency Function

• General Form– FormatCurrency(NumericExpression)

• 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

Page 24: Chapter 3 Variables, Constants and Calculations Programming In Visual Basic.NET

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

FormatNumber Function

• General Form– FormatNumber(NumericExpression

[ , 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

Page 25: Chapter 3 Variables, Constants and Calculations Programming In Visual Basic.NET

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

FormatPercent Function

• General Form– FormatPercent(NumericExpression

[, 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

Page 26: Chapter 3 Variables, Constants and Calculations Programming In Visual Basic.NET

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

FormatDateTime Function

• General Form– FormatDateTime(Expression [, Named Format] )

• Expression can be:– String that holds a date or time– Date type variable

Page 27: Chapter 3 Variables, Constants and Calculations Programming In Visual Basic.NET

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

Named Formats - FormatDateTime Function

Named Format ExampleDateFormat.GeneralDate 2/28/99 6:01:24 PMDateFormat.ShortDate 2/28/99DateFormat.LongDate Sunday, February 28, 1999DateFormat.ShortTime 18:01(24 Hour Clock)DateFormat.LongTime 6:01:24 PM

Page 28: Chapter 3 Variables, Constants and Calculations Programming In Visual Basic.NET

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

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

Page 29: Chapter 3 Variables, Constants and Calculations Programming In Visual Basic.NET

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

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

Page 30: Chapter 3 Variables, Constants and Calculations Programming In Visual Basic.NET

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

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

See p 111 for list of common Exception Classes

Page 31: Chapter 3 Variables, Constants and Calculations Programming In Visual Basic.NET

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

Try Block - Example 1Catches All Exceptions

TryintQuantity=CInt(txtQuantity.Text)lblQuantity.Text=CStr(intQuantity)

CatchlblMessage.Text="Error in input data."

End Try

Page 32: Chapter 3 Variables, Constants and Calculations Programming In Visual Basic.NET

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

Try Block - Example 2Catches Specific Exception

TryintQuantity=CInt(txtQuantity.Text)lblQuantity.Text=CStr(intQuantity)

Catch MyErr as InvalidCastExceptionlblMessage.Text="Error in input data."

End Try

Conversion exception, usually caused by nonnumeric or blank data

Page 33: Chapter 3 Variables, Constants and Calculations Programming In Visual Basic.NET

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

Try Block - Example 3Catches Multiple Specific ExceptionsTry

statements that may cause errorsCatch MyErr as InvalidCastException

error messages and statements for nonnumeric data Catch MyErr as ArithmeticException

error messages and statements for calculation problemsCatch MyErr as Exception

error messages and statements for any other exceptionEnd Try

Page 34: Chapter 3 Variables, Constants and Calculations Programming In Visual Basic.NET

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

MessageBox Object

• Use Show Method of MessageBox to display special type of window

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

Page 35: Chapter 3 Variables, Constants and Calculations Programming In Visual Basic.NET

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

MessageBox Syntax

MessageBox.Show (TextMessage, TitlebarText, _ MessageBoxButtons, MesssageBoxIcon)

• The MessageBox 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

Page 36: Chapter 3 Variables, Constants and Calculations Programming In Visual Basic.NET

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

MessageBoxButtons Constants

• OK

• OKCancel

• RetryCancel

• YesNo

• YesNoCancel

• AbortRetryIgnore

Page 37: Chapter 3 Variables, Constants and Calculations Programming In Visual Basic.NET

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

MessageBoxIcon Constants

• Asterisk• Error• Exclamation• Hand• Information

• None• Question• Stop• Warning

Page 38: Chapter 3 Variables, Constants and Calculations Programming In Visual Basic.NET

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

Counting & Accumulating Sums

• Must use Module/Form level variables since Local/Event level variables reset to 0 each time the procedure is called

• Summing– mdecOrderTotal = mdecOrderTotal + decItemPrice

• Counting– mintNumItems = mintNumItems + 1

– mintNumItems += mintNumItems

• Averaging– mdecAveSale = mdecOrderTotal / mintNumItems