Presentation is loading. Please wait.

Presentation is loading. Please wait.

IS 1181 IS 118 Introduction to Development Tools VB Chapter 04.

Similar presentations


Presentation on theme: "IS 1181 IS 118 Introduction to Development Tools VB Chapter 04."— Presentation transcript:

1 IS 1181 IS 118 Introduction to Development Tools VB Chapter 04

2 Copyright (c) 2003 by Prentice Hall Chapter 4 Data, Operations, and Built-In Functions Visual Basic. NET

3 IS 1183 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

4 IS 1184 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

5 IS 1185 Classification of Data MsgBox(“Your age is “ & 24)  Text 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

6 IS 1186 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

7 IS 1187 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

8 IS 1188 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

9 IS 1189 Declaring Variables Declared with the Dim statement Must give the variable a name  Optionally, define data type Although it’s only optional, you should specify data type  Can use type suffixes for data types Code suffixes hard to read and understand  Syntax: Dim MyID as Long Defines a variable named MyID as a long data type

10 IS 11810 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

11 IS 11811 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

12 IS 11812 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

13 IS 11813 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

14 IS 11814 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)

15 IS 11815 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

16 IS 11816 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

17 IS 11817 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 MyIDNum as Integer  Private access – not visible to other modules Private MyIDNum as Integer

18 IS 11818 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

19 IS 11819 Declaring Objects To use object data types in code is a two-step process  Declare variable of that class type Dim M as Math declares M as an variable of Math type  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

20 IS 11820 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

21 IS 11821 Data Types of Limited Values Byte – uses one character  Often used to handle ASCII code data Char – uses two characters  Often used to handle Unicode code data Neither type handles negative numbers Boolean – stores logical value of True or False

22 IS 11822 Data Types for Whole Numbers Can handle positive or negative numbers, but no decimal places Range of numbers determined by storage size  Short Requires 2 bytes of storage  Integer Requires 4 bytes of storage  Long Requires 8 bytes of storage

23 IS 11823 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)

24 IS 11824 Characteristics of Numeric Types

25 IS 11825 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

26 IS 11826 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

27 IS 11827 Numeric Operations Code on right side referred to as expression  Can be a constant, a variable, or any numeric operation

28 IS 11828 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

29 IS 11829 An Application Example: Computing Net Sales Analyze and define requirements  An application to compute net receipts Determine controls needed  Mainly labels and text boxes  Right align text boxes so decimal places line up Declaring 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

30 IS 11830 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

31 IS 11831 Computing Total Receipts CreditCardRate defined as class-level constant FmtStandard defined as class-level constant

32 IS 11832 The Visual Interface All text boxes have the same format, right-aligned with two decimal places

33 IS 11833 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

34 IS 11834 Conversion Functions Used to explicitly convert a variable from one data type to another

35 IS 11835 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

36 IS 11836 Common String Functions

37 IS 11837 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

38 IS 11838 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 the Price  Price will be a string in the list box Must convert into a number

39 IS 11839 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

40 IS 11840 Loading the Form Class-level variables used by several event procedures

41 IS 11841 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

42 IS 11842 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

43 IS 11843 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

44 IS 11844 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


Download ppt "IS 1181 IS 118 Introduction to Development Tools VB Chapter 04."

Similar presentations


Ads by Google