0% found this document useful (0 votes)
44 views44 pages

IS 118 Introduction To Development Tools: VB Chapter 04

VB Chapter Important

Uploaded by

Subarna Lamsal
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
44 views44 pages

IS 118 Introduction To Development Tools: VB Chapter 04

VB Chapter Important

Uploaded by

Subarna Lamsal
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 44

IS 118 Introduction to

Development Tools
VB Chapter 04

IS 118

Chapter 4
Data, Operations, and Built-In
Functions
Visual Basic. NET

Copyright (c) 2003 by Prentice Hall

Objectives
Differentiate

among different types of data


Declare data types properly for constants
and variables
Appreciate the importance of having the
IDE check variables for their declaration
Differentiate and appreciate the
implications of the scope and lifetime of
variables under different declarations
IS 118

Objectives
Understand

the nature of the assignment

statement
Recognize and use various arithmetic
expressions and functions
Understand the usefulness of strict type
checking
Recognize and use various string functions
Understand better how data and VB controls are
used together in a project
IS 118

Classification of Data
MsgBox(Your
Text

age is & 24)

in quotation marks is a string

Text

can be manipulated, but no computations

Numeric

data can be used for computation

Data

must be kept in memory before it can


be retrieved for manipulation,
computation, or display

IS 118

Using Memory Locations


Give

memory locations a name and refer


to the name
If data expected to change, classify as
variable
If data not expected to change, classify as
constant
Named

constant: a constant given a name and


referenced accordingly
IS 118

Declaring Constants
Some

constants are predefined

Known

as system constants
Examples include True and False
Others

defined and declared before used

Known

as symbolic constants
Must be declared with Const statement
To

declare a constant: Const MyName = Tom


McKenzie
Defines the constant MyName and assigns a value
IS 118

Why Use Constants?


Makes

code easier to read and trace


To change the value of a constant, change
it where it is declared
Change

will be reflected throughout system

Name

all constants for your program in


one location

IS 118

Declaring Variables
Declared

with the Dim statement


Must give the variable a name
Optionally,
Although

define data type


its only optional, you should specify data

type
Can

use type suffixes for data types

Code

Syntax:

suffixes hard to read and understand

Dim MyID as Long

Defines

a variable named MyID as a long data type


IS 118

Checking for Variable Declaration


Option

Explicit statement determines


whether VB requires variable declaration
When

set to Off, VB will not require declaration

Default

is On, so variables must be


declared before they can be used
Get in the habit of requiring declaration

IS 118

10

Why Require Declaration?


An

undeclared or misspelled variable can


give unexpected results
You

can spend hours tracing bugs

Helps

you catch syntax errors


When you use variables in code, VB will
enforce same capitalization as when
declared

IS 118

11

Rules for Declaration


Can

contain any combination of letters and


numbers
Can begin with letter or underscore, but not a
number

Must have at least one letter or digit if it begins with an


underscore

Cannot

contain spaces
If it has same name as a reserved keyword, i.e.
Date, must be enclosed with brackets
Cannot contain embedded periods or data suffix
characters
IS 118

12

Scope and Lifetime of Variables


Scope

refers to how widely variable is


recognized throughout program
Lifetime refers to how long a variable
remains in computer memory

IS 118

13

Class-Level Variables
Code

window associated with form referred to as


class module
Class level variables declared in general
declarations area (before any code is entered)
with Dim statement
Scope: recognized by all procedures in the class
Lifetime: created when form is loaded and
remain in memory until form is destroyed (closed)

IS 118

14

Procedure-Level Variables
Declared

inside a procedure

Also called local variables

Scope:

only recognized within the procedure


Lifetime: depends on how declared

If declared with Dim keyword, reinitialized every time the


procedure is called
String variables reinitialized to an empty string
Numeric variables reinitialized to 0

If declared with Static keyword, values preserved rather


than reinitialized every time the procedure is called

Destroyed when form is destroyed


IS 118

15

Declaration Issues
Block-level

declaration:

If declared within an If block, recognized only within the


block

Overlapping

declarations:

When variable with same name declared at class level


and procedure level, VB uses the memory location with
the narrowest type

Take care not to overlap

In

general, declare variables at narrowest


possible scope
IS 118

16

Access Modifiers
With

class-level variables, you need to


decide whether they will be accessible to
other modules in the project
Instead of declaring with Dim statement,
use Public or Private keyword
Public

access visible to other modules

Public

Private

MyIDNum as Integer

access not visible to other modules

Private

MyIDNum as Integer
IS 118

17

Objects
An

object is actually an instance of a class

Think

of the class as a template


Object is created as an instance of that class
Process

called instantiation

IS 118

18

Declaring Objects
To use

object data types in code is a two-step


process
Declare variable of that class type
Dim

type

M as Math declares M as an variable of Math

Create an instance of that class


requires

the New keyword


M = New Math() associates the variable M with an
instance of the Math object

Can do both in one statement with most objects


Dim

M as New Math() combines the two previous


statements
IS 118

19

Numeric Data and Types


Many

different ways to store and handle


numbers
Precision of data type refers to accuracy in
handling significant digits
Inadequate

precision can lead to significant


rounding error in calculations

Different

types require different amounts


of storage
IS 118

20

Data Types of Limited Values


Byte

uses one character

Often

Char

used to handle ASCII code data

uses two characters

Often

used to handle Unicode code data

Neither

type handles negative numbers


Boolean stores logical value of True or
False
IS 118

21

Data Types for Whole Numbers


Can

handle positive or negative numbers, but no


decimal places
Range of numbers determined by storage size

Short

Integer

Requires 2 bytes of storage


Requires 4 bytes of storage

Long

Requires 8 bytes of storage

IS 118

22

Data Types for Mixed Numbers


Uses

floating point coding scheme

Mantissa: stores base value of data


Exponent: stores how the mantissa is raised (to
the power of 10)

Different

types handle different numbers of


significant digits and need different storage
Single: 7 significant digits (4 bytes storage)
Double: 15 significant digits (8 bytes storage)
Decimal: 29 significant digits (16 bytes storage)

IS 118

23

Characteristics of Numeric Types

IS 118

24

Implicit Type Conversion


Often

bugs are created when the compiler


converts different data types

Can use data conversion functions to explicitly


convert data type by code

Option

Strict On forces you to observe strict


data conversion rules

You can implicitly convert from narrower type to


wider (e.g., from Integer to Long)

To convert to narrower type, use data conversion


functions

You

should use this option to avoid


unexpected data conversion errors
IS 118

25

Assignment Statement
OvertimePay

= StandardPay * 1.5 moves data


resulting from the operation on the right side to
the memory location on the left

Variable on right must be properly declared before


operation can be moved to left
Variable on left must have the capacity to handle the
result of the operation on the right

if not, an overflow error occurs

Left side must be a variable or a control property whose


value can be set at run time

txtOT.Text = StandardPay * 1.5 is a valid assignment


statement

IS 118

26

Numeric Operations
Code

on right side referred to as expression

Can be a constant, a variable, or any numeric


operation

IS 118

27

Operational Precedence
Order

of Preference

Power
Unary negation
Multiplication and division
Integer division
Mod
Addition and subtraction

To enforce

a different order or eliminate confusion,


enclose expression in parentheses

IS 118

28

An Application Example:
Computing Net Sales
Analyze

and define requirements

An application to compute net receipts

Determine

Mainly labels and text boxes


Right align text boxes so decimal places line up

Declaring

controls needed

variables and constants

Use variables to hold data entered into text boxes


Use a constant to hold credit card processing rate
Use variables to hold net processing and net receipts
IS 118

29

An Application Example:
Computing Net Sales
Computations
Decide

when to store information entered in text

boxes
Create formulas for computation
Decide how to display result of computations
Format

function displays results with defined format

IS 118

30

Computing Total Receipts

CreditCardRate defined as class-level


constant

FmtStandard defined as class-level


constant

IS 118

31

The Visual Interface

All text boxes have the


same format, right-aligned
with two decimal places

IS 118

32

Built-In Numeric Functions


Mathematical

Functions

Rnd function generates a random number >= 0.0 and <


1.0

Often used in simulations

Math

Object contains many built-in methods for


computations

Examples include Abs (absolute value) and Sqrt (square


root)

Date/Time

functions return a number of date or


time related values

Today returns the system date as defined on the computer


IS 118

33

Conversion Functions
Used

to explicitly convert a variable from


one data type to another

IS 118

34

String Data
Declared

with the String data type


All strings are variable-length strings
String Operations:
Concatenation

combines 2 strings
Valid concatenation operators: & and +
If

you use + and either string contains only numbers,


you will get unexpected results
You should always use & to concatenate

IS 118

35

Common String Functions

IS 118

36

An Application Example:
The Calculating Vending Machines
Analyze

and define the requirements


A form a user can use to purchase items
User

will select an item from a list box

Setting

Up the Vending Machine


Use the Items.Add method of the list
Create

2 columns in the list by including a tab


character (vbTab) between item and price
Use the With block to add multiple items save
keystrokes adding the items

IS 118

37

Application Example:
The Calculating Vending Machine
Determining

the Item Chosen

Must

determine name chosen


Must also determine price for item
Displaying

Selected Items

If

user selects more than one item, must


concatenate into a single string

Obtaining
Price

the Price

will be a string in the list box

Must

convert into a number


IS 118

38

Application Example:
The Calculating Vending Machine
Accumulating the total
When user selects an item, the cost must be added to
the accumulated total
Declaring variables
Give special consideration to scope and type

Precision will be very important

Checking out
Need a mechanism to allow user to indicate he/she has
finished ordering
Need a routine in case the user checks out without
buying anything
Reinitialize class-level variables after checking out
IS 118

39

Loading the Form

Class-level variables used by several


event procedures

IS 118

40

Calculating Items Bought

Tab divides line into


fields, use InStr function
to find Tab
Add carriage return and item to
class-level ItemsBot variable
Accumulate total; must
convert text to single

IS 118

41

Summary

Data can be classified into two broad categories: numeric


and string
Data can be classified into variables and constants
Variables require a name
Constants do not require a name, though it is advisable
Constants declared with keyword Const
Variables declared with either Dim or Static keyword
Variables and constants classified by scope
If declared at class level, recognized by all procedures in
the class
If declared within procedure, recognized only by that
procedure

IS 118

42

Summary

Variables and constants classified by lifetime

If declared at class level, they exist as long as class (form) exists


If declared inside procedure with Dim keyword, reinitialized every time
the procedure is called
If declared inside procedure with Static keyword, they exist as long as
the class exists
If declared inside block, they are out of scope as soon as the block is
terminated

Declare variables with as narrow a scope as possible


Declare constants with as broad a scope as possible
Numeric data can be classified into different types, for
different computational needs

IS 118

43

Summary
VB

can perform a wide range of mathematical


operations
VB provides many built-in mathematical,
date/time and data conversion functions
VB provides many functions for manipulating
string data
The Format function can be used to format
numeric data
Use the Option Strict On setting to enforce
explicit data conversion
IS 118

44

You might also like