irwin/mcgraw-hill © the mcgraw-hill companies, inc., 1999 3-1 representing data constants and...
DESCRIPTION
Irwin/McGraw-Hill © The McGraw-Hill Companies, Inc., Data item Decisions required to specify a data item in VB TRANSCRIPT
3-1
© The McGraw-Hill Companies, Inc., 1999
Irwin/McGraw-Hill
Representing DataConstants and Variables
chapter THREE
3-2
Representing DataConstants and Variables
After studying this topic you should be able to: Differentiate between numeric and string data. Determine whether a data item should be a constant
or variable. Code constants and variables in event procedures. Describe the characteristics and uses of standard data
types. Explain scope and describe the domain of variables in
event procedures and forms. Create projects that consist of several forms.
3-3
© The McGraw-Hill Companies, Inc., 1999
Irwin/McGraw-Hill
Data item
Decisions required to specify a data item in VB
3-4
© The McGraw-Hill Companies, Inc., 1999
Irwin/McGraw-Hill
Data item
String
Constant Variable
Decisions required to specify a data item in VB
3-5
© The McGraw-Hill Companies, Inc., 1999
Irwin/McGraw-Hill
Data item
String Numeric
Constant VariableConstant Variable
First decision: numeric or string
Second decision:
constant or variable
Decisions required to specify a data item in VB
Irwin/McGraw-Hill
© The McGraw-Hill Companies, Inc., 1999
3-6
String Values
A collection of printable symbols. Synonym: textExample:
“CNS 1200”“Visual Programming 1 – Visual Basic ”“It was a dark and stormy night”
Must be printable ANSI charactersSee ANSI table p. 175
Irwin/McGraw-Hill
© The McGraw-Hill Companies, Inc., 1999
3-7
Numeric values Numbers that may be used in arithmetic
calculations Examples:13 14.6 -8.77 -0.023 001.800 -.023 ‘0 to left of the decimal not required 001.800 ‘leading 0’s ignored - trailing 0’s contain
information, carried if possible 8.9E-6 = 0.0000089 1.34E+3 = 1340. Note: no commas or $ in the number
3-8
© The McGraw-Hill Companies, Inc., 1999
Irwin/McGraw-Hill
Classification of constants in VB
Numeric or stringconstant
SymbolicLiteral
Irwin/McGraw-Hill
© The McGraw-Hill Companies, Inc., 1999
3-9
Constants
Fixed at run timeCannot be changedLiteral constant
- the value itselfSymbolic constant
- PI = 3.1416
Irwin/McGraw-Hill
© The McGraw-Hill Companies, Inc., 1999
3-10
Symbolic Constant
Use a symbol - SALESTAXRATE - defined once, used many times
Name - 255 characters letters & numbers1st character must be a letterSpaces not allowed, SALES_TAX_RATEReserved words not allowed - problemAll Caps is the convention
Irwin/McGraw-Hill
© The McGraw-Hill Companies, Inc., 1999
3-11
Defining & Declaring Constants
Const is a reserved word used to declare an immutable value and its symbolic name
Examples:Const SALES_TAX_RATE = 0.081Const COMPANY_ADDRESS =
“347 Main Street, Orem UT, 84058”Const DISK_ERR= “There is no disk in A:”
Irwin/McGraw-Hill
© The McGraw-Hill Companies, Inc., 1999
3-12
No Magic Numbers
Only 0, 1, -1, “” allowed as literal constantsNamed constant easier to understandConstant reduces a the chance for typosMakes a change throughout the program easy
and correct, especially when the same value used for two different purposes.
TAX_RATE goes from 0.081 to 0.086Const SHIPPLING_PER_TON = .081
Irwin/McGraw-Hill
© The McGraw-Hill Companies, Inc., 1999
3-13
Visual Basic Constants
Shipped as a part of Visual BasicA large number related to various objectsBackColor, ForeColor, …
vbRed, vbYellow, vbBlue, vbGreen …Alignment
vbLeftJustify, vbRightJustify, vbCenter
Irwin/McGraw-Hill
© The McGraw-Hill Companies, Inc., 1999
3-14
New Line Constant
Used in many languages for a carriage return and a line feed
CHR(13) = Carriage returnCHR(10) = Line feedvbNewLine = CHR(13) + CHR(10)
Irwin/McGraw-Hill
© The McGraw-Hill Companies, Inc., 1999
3-15
Which are Valid Constant Definitions?
In-class exercise 3.2
Irwin/McGraw-Hill
© The McGraw-Hill Companies, Inc., 1999
3-16
Variables
A named memory location used as temporary holder
Current value is replaced forever by the new Declaration DIM Name as String
Variable name Variable data type
Initialization Name = “The Wolverine” VB provides default values
Numeric variables 0 String variables “” (empty string )
Irwin/McGraw-Hill
© The McGraw-Hill Companies, Inc., 1999
3-17
Variable Names Name must be unique & should be meaningful Keywords may not be used as variable names Case Insensitive - but matches the Dim Dim is the keyword used to tell VB to
Give it a name - to be used later in the program Set aside an amount of memory
Name 255 characters, 1st letter alphabetic no spaces or special characters %, @, ., #, !, $
Irwin/McGraw-Hill
© The McGraw-Hill Companies, Inc., 1999
3-18
Which are Valid Variable Names?
In-class exercise 3.3
Irwin/McGraw-Hill
© The McGraw-Hill Companies, Inc., 1999
3-19
Data Types Defined in VBString
Variable lengthFixed length
NumbersInteger, Long, Single, Double, Currency
Others including VariantAvoid Variant in this course
User defined
Irwin/McGraw-Hill
© The McGraw-Hill Companies, Inc., 1999
3-20
Data RepresentationStrings
“Visual Basic is easy to learn and use.”“Jones” “X” “286 Main Street” “3”“” ‘ The empty string
Numbers (can be used for arithmetic)286-308.45514259578374679.00974
Irwin/McGraw-Hill
© The McGraw-Hill Companies, Inc., 1999
3-21
Numeric data types
Whole numbers 37 -842Integer - smallLong - big
Fractional numbers 37.7223 -842.01Single - BigDouble - BiggerCurrency - Bigger without rounding errors
Irwin/McGraw-Hill
© The McGraw-Hill Companies, Inc., 1999
3-22
String Data Type
Variable length -- 2 Billion max Example:
Dim FirstName as StringFirstName = “Christopher” FirstName= “Victoria”
Size changes automatically Memory Size: 10 bytes + 1 byte per character
Fixed length -- 65,400 max Example:
Dim ZipCode as String * 5ZipCode = “48058”
Memory Size: 1 byte per character
Irwin/McGraw-Hill
© The McGraw-Hill Companies, Inc., 1999
3-23
Fixed String Data Type
Required for Arrays and Record (Structure)Memory - Byte per space (here 26)Dim City as String * 26Unused space is filled by NULL charactersOverflow is truncated
Irwin/McGraw-Hill
© The McGraw-Hill Companies, Inc., 1999
3-24
String Concatenation &
Appends one string to the end of another string
Example:String1 = “The big bad”String2 = “wolf.”String3 = String1 & String2String3 now contains The big badwolf.
Irwin/McGraw-Hill
© The McGraw-Hill Companies, Inc., 1999
3-25
Integer Data Type
Whole number 89, -37, -32768, ?32840?Memory set aside 2 BytesMaximum Size +-32K (-32768 to +32767) Example:
Dim Age as IntegerAge = 100
Fractional values are dropped
Irwin/McGraw-Hill
© The McGraw-Hill Companies, Inc., 1999
3-26
Long Data Type
Whole number 89, -37, -32768, 32840Memory Set aside 4BytesMaximum Size very big
-2,147,843,648 to 2,147,843,647 Example:
Dim BankBalance as Long ‘4 bytesBankBalance = 1000895 ‘ No comma’s
Irwin/McGraw-Hill
© The McGraw-Hill Companies, Inc., 1999
3-27
Single Data Type
Fractional number 89.6 -37.0 .00006 Maximum - Big number (+- 1.4E-45 to 3.4E38) Memory Set aside 4 Bytes 7 Significant Digits
1.7894288 .00017894288 17894288 Example:
Dim Wage as SingleWage = 5.90
Irwin/McGraw-Hill
© The McGraw-Hill Companies, Inc., 1999
3-28
Double Data Type
Fractional number 89.6 -37.0 .000061.7894288 .00017894288 17894288
Maximum - Very big (+- 4.9324 to 1.8E308)Memory Set aside 8 Bytes15 Significant Digits
-.0009787658654388955 9875.86445679987
Irwin/McGraw-Hill
© The McGraw-Hill Companies, Inc., 1999
3-29
Currency Data Type
Fractional number with 4 decimal places Maximum Very big (15.4 digits)Memory Set aside 8 BytesExample:
Dim HouseLoan as Currency HouseLoan = 111211121112765.9999
No rounding errors for money calculations
Irwin/McGraw-Hill
© The McGraw-Hill Companies, Inc., 1999
3-30
Decision rules for Standard Data Types
Math to be done
Size change?
F String !
V String !
Currency?
Currency !
NoYes
NoNo Yes
Yes
Irwin/McGraw-Hill
© The McGraw-Hill Companies, Inc., 1999
3-31
Decision rules for Math Data Types
Decimals?
> 7 Digits ? > 32 K ?
Single
Double Long
Integer
No
No No
Yes
Yes Yes
Irwin/McGraw-Hill
© The McGraw-Hill Companies, Inc., 1999
3-32
Review of Standard Data Types
Type Bytes LimitString 10 + character 2,000,000,000Integer 2 +- 32 KLong 4 +- 2 BillionSingle 4 7 digitsDouble 8 15 digitsCurrency 8 15.4 digits
Irwin/McGraw-Hill
© The McGraw-Hill Companies, Inc., 1999
3-33
Defining, Declaring and Initializing Variables
Dim VariableName as DataTypeExamples:
Dim Name as String ‘ Empty stringName = “Jones”Dim Age as Integer ‘ 0 value enteredAge = 84Dim WageRate as Single ‘ 0.0 value enteredWageRate = 5.76
Irwin/McGraw-Hill
© The McGraw-Hill Companies, Inc., 1999
3-34
Variable LifetimeLocal level variables
Created when Function/Sub calledDie when Function/Sub is exited
Form level variablesCreated when Form is Loaded into memoryDie when Form is un-Loaded from memory
Global variablesCreated when program startsDie when program terminates
Irwin/McGraw-Hill
© The McGraw-Hill Companies, Inc., 1999
3-35
Variable Lifetime
Local - while code runsExcept Static variables
Module - while the Form runsGlobal - while the Program runs
Allows re-use of memory
Irwin/McGraw-Hill
© The McGraw-Hill Companies, Inc., 1999
3-36
Variable Scope
Depends on where and how declaredScope How DeclaredLocal Dim, Static, ReDimModule Dim, PrivateGlobal Global, Public
Right mouse click will show properties of variable
Irwin/McGraw-Hill
© The McGraw-Hill Companies, Inc., 1999
3-37
Local variables
Variable ValueMyName “John Doe”
Variable ValueMyName “ ”
Irwin/McGraw-Hill
© The McGraw-Hill Companies, Inc., 1999
3-38
Variable ValueMyName “John Doe”
Variable Value
Variable Value
Module-level variable
Irwin/McGraw-Hill
© The McGraw-Hill Companies, Inc., 1999
3-39
Variable ValueMyName “John Doe”
Variable Value
Variable Value
Module-level variable
Irwin/McGraw-Hill
© The McGraw-Hill Companies, Inc., 1999
3-40Local variable hides module-level variable with same name
Variable Value
Variable ValueMyName “John Doe”YourName “Mary Smith”
Variable ValueYourName “ ”
Irwin/McGraw-Hill
© The McGraw-Hill Companies, Inc., 1999
3-41
Variable Value
Variable Value
Variable ValueOurName “John Doe”
Variable Value
Variable Value
A globalvariable
Irwin/McGraw-Hill
© The McGraw-Hill Companies, Inc., 1999
3-42
The three levels of variable
scope
A local variable is declared in an event
procedure using a Dim statement. It
can be accessed only in the event
procedure in which it is declared.
3-43
Use
r in
terf
ace
Cod
e
The three levels of variable
scope
FormfrmTestA
A module-level variable is declared in
the general declarations section containing the Dim
statement. It can be accessed by any event
procedure on the same form as the general
declarations statement.
Irwin/McGraw-Hill
© The McGraw-Hill Companies, Inc., 1999
3-44
Form frmTestA
Code module modTest
Project
Use
r in
terf
ace
Cod
e
Cod
e
Global Variablesare declared in the general declarations section of a code module using the Public statement, and can be accessed by the code in any event procedure anywhere in the project.
Irwin/McGraw-Hill
© The McGraw-Hill Companies, Inc., 1999
3-45
Static vs Dim
Initializes variable the first time only, then the value is maintained for the remainder of the life of the program. Reuse of the variable (by entering the procedure), does not reinitialize the variable. Scope is unchanged.
Example:Static Joe As IntegerDim Joe As Integer
Irwin/McGraw-Hill
© The McGraw-Hill Companies, Inc., 1999
3-46
Assignment operator =
Target = Source ‘ required direction 3 = A if A = 7 and B = 2 then after A = B what
is contained in both A and B ???Target must be a variableRight side of equation is completely
evaluated, then transferred over =Implicit type conversion will occur unless
explicit conversion by programmer
Irwin/McGraw-Hill
© The McGraw-Hill Companies, Inc., 1999
3-47
Type Mismatch error
Trying to put a golf club in a gallon jug.Dim x as Integerx = “14 inches” ‘ Errorx = 14.99 ‘No Error auto truncation to
14Run time error - Depends on values when
the program is running so can’t be tested.
Irwin/McGraw-Hill
© The McGraw-Hill Companies, Inc., 1999
3-48
Changes to the Propertyof a Control
Label1.Caption = “New Caption”Label2.Caption = Label1.CaptionMost properties can be Set or ReadMost properties can changeSome (Name, Tag,…) can not be changedSome are “Read only at run time” and can
not be changed
Irwin/McGraw-Hill
© The McGraw-Hill Companies, Inc., 1999
3-49
Public vs Private code
Public changes all variables to GlobalAllows the code to be used by othersViolates good programming practices
Avoid Globals
Irwin/McGraw-Hill
© The McGraw-Hill Companies, Inc., 1999
3-50
Methods vs Properties
Object.Method vs. Object.PropertyProperties
Store a Numeric or string valueCan be used in an assignment statement
MethodsCannot be used in assignment statementsMust be on a line by itself
Irwin/McGraw-Hill
© The McGraw-Hill Companies, Inc., 1999
3-51
Additional Data Types
Byte 0 to 255Boolean True or FalseDate Jan,1, 100; Dec.31,9999Variant Any numeric or string valueObject (reference) User defined – Structures (records), Classes
Irwin/McGraw-Hill
© The McGraw-Hill Companies, Inc., 1999
3-52
Byte Data Type
Whole positive number 0, 89, 255Memory set aside 1 ByteMaximum range 0 to 255Dim Age As ByteAge =100
Irwin/McGraw-Hill
© The McGraw-Hill Companies, Inc., 1999
3-53
Boolean Data Type
True or FalseMemory set aside 2 Bytes
Irwin/McGraw-Hill
© The McGraw-Hill Companies, Inc., 1999
3-54
Date Data Type
Contains both date and time information Date.TimeMemory set aside 8 BytesDate Jan.1, 100 to Dec.31, 9999Time 00:00:00 to 23:59:59
Noon = .5000, Midnight or 00:00:00 = 0
Irwin/McGraw-Hill
© The McGraw-Hill Companies, Inc., 1999
3-55
Variant Data Type
Default data type Memory set aside 17 BytesWill hold any data type (Byte, Boolean,
Date, Double, Integer, Long, Single, String, Objects) and Empty, Error, Nothing, Null
type = VarTyp (variable name) ‘defines type of variable contained
Irwin/McGraw-Hill
© The McGraw-Hill Companies, Inc., 1999
3-56
Object Data Type
A reference to an objectDo not use LetUse Set
Irwin/McGraw-Hill
© The McGraw-Hill Companies, Inc., 1999
3-57
Multiple FormsAll the code is associated with the form and
its controls and is stored in the .frm fileLoad event occurs whenever a form is
displayedForm.Load -code is placed in RAMForm.Unload -code is removed from RAMForm.Show - Loads & Displays the formForm.Hide -Removes from display (but
still in RAM)
Irwin/McGraw-Hill
© The McGraw-Hill Companies, Inc., 1999
3-58
More than one form in a project
Add form to projectEach form’s controls have access to
themselves or the controls on other formsForm1.Label1.BackColor =
Form2.BackColorCycle from one form to another with Hide
& Show properties.
Irwin/McGraw-Hill
© The McGraw-Hill Companies, Inc., 1999
3-59
Adding & Deleting a Form
Adding a new form to a projectUse New Form Icon or Project New FormProject Explorer shows the additional form
Deleting a form from a projectHighlight in Project Explorer windowProject Remove Form
New forms generate a new file when saved
Irwin/McGraw-Hill
© The McGraw-Hill Companies, Inc., 1999
3-60
Typical Contents of .frm fileVERSION 5.00Begin VB.Form Form1 Caption = "Assign01-Gross Pay Calculator" ClientHeight = 3465 ClientLeft = 1545 ClientTop = 1965 ClientWidth = 3600 BeginProperty Font Name = "MS Sans Serif" Size = 8.25 Charset = 0 Weight = 700 Underline = 0 'False…
Irwin/McGraw-Hill
© The McGraw-Hill Companies, Inc., 1999
3-61
Contents of .vbp fileType=ExeForm=Assign2.FRMReference=*\G{00025E04-0000-0000-C000-
000000000046}#3.5#0#..\..\..\..\..\..\..\PROGRAM FILES\COMMON FILES\MICROSOFT SHARED\DAO\dao2535.tlb#Microsoft DAO 2.5/3.0 Compatibility Library
IconForm="Form1"Startup="Form1"ExeName32="Assign2.exe"Command32=""Name="Prob2"HelpContextID="0"
Irwin/McGraw-Hill
© The McGraw-Hill Companies, Inc., 1999
3-62
Lab: Data Types
Complete Exercise 3.16