Chapter 3 Using Variables and Constants Programming with
Chapter 3: Using Variables and Constants Programming with Microsoft Visual Basic 2005, Third Edition
Creating Variables and Named Constants Lesson A Objectives • Declare variables and named constants • Assign data to an existing variable • Convert string data to a numeric data type using the Try. Parse method • Convert numeric data to a different data type using the Convert class methods Programming with Microsoft Visual Basic 2005, Third Edition 2
Creating Variables and Named Constants Lesson A Objectives (continued) • Explain the scope and lifetime of variables and named constants • Explain the purpose of the Option Explicit and Option Strict statements Programming with Microsoft Visual Basic 2005, Third Edition 3
Previewing the Completed Application • Previewing the Skate-Away Sales application – Access the Run command on the Start menu – Browse to the VB 2005Chap 03 folder – Open the Skate. Away (Skate. Away. exe) file – View the completed order form • Completed application resembles Chapter 2 version Programming with Microsoft Visual Basic 2005, Third Edition 4
Previewing the Completed Application (continued) Figure 3 -1: Name Entry dialog box Programming with Microsoft Visual Basic 2005, Third Edition 5
Using Variables to Store Information • Controls and variables temporarily store data • Variable – Temporary storage location in main memory – Specified by data type, name, scope, and lifetime • Reasons to use variables – Allows for more precise treatment of numeric data – Enables code to run more efficiently Programming with Microsoft Visual Basic 2005, Third Edition 6
Selecting a Data Type for a Variable • Data type – Specifies type of data variable can store – Provides a class template for creating variables • Integer variables: Integer, Long, Short • Floating-point number – Expressed as a power of 10 – Written in E (exponential) notation; e. g. , 3. 2 E 6 • Floating-point variables: Single, Double Programming with Microsoft Visual Basic 2005, Third Edition 7
Selecting a Data Type for a Variable (continued) • • • Fixed decimal point variable: Decimal Character variable: Char Text variable: String Boolean variables: True, False The Object variable – Default data type assigned by Visual Basic – Can store many different types of data – Less efficient than other data types Programming with Microsoft Visual Basic 2005, Third Edition 8
Selecting a Name for a Variable • Variables are referred to by name • Identifier: another term for a variable name • Basic guidelines for naming variables – Name should be descriptive; e. g. , length and width – Enter the name in camel case; e. g. , sales. Amount • Certain rules must be followed – Example: a name begins with a letter or underscore Programming with Microsoft Visual Basic 2005, Third Edition 9
Selecting a Name for a Variable (continued) Figure 3 -4: Rules for variable names along with examples of valid and invalid names Programming with Microsoft Visual Basic 2005, Third Edition 10
Declaring a Variable • Declaration statement – Used to declare, or create, a variable • Syntax: {Dim | Private | Static} variablename [As datatype][= initialvalue] • Examples – Dim hours. Worked As Double ‘note: no initial value – Dim is. Data. Ok As Boolean = True ‘ variable initialized – Dim message As String = “Good Morning” Programming with Microsoft Visual Basic 2005, Third Edition 11
Assigning Data to an Existing Variable • Assignment statement – Assigns a value to a variable at runtime • Syntax: variablename = value – Example: quantity. Ordered = 500 • Literal constant: data item that does not change – Example: the string “Mary” • Literal type character: changes type of a literal – Example: sales = 2356 R ‘ integer cast to Double Programming with Microsoft Visual Basic 2005, Third Edition 12
Assigning Data to an Existing Variable (continued) Figure 3 -7: Literal type characters Programming with Microsoft Visual Basic 2005, Third Edition 13
The Try. Parse Method • Syntax: data. Type. Try. Parse(string, variable) – data. Type: numeric data type, such as Integer – Try. Parse method is a member of data. Type class – string argument: string to convert to a number – variable argument: names numeric storage unit • Example – Dim sales As Decimal. Try. Parse(Me. x. Sales. Text. Box. Text, sales) Programming with Microsoft Visual Basic 2005, Third Edition 14
The Convert Class • Syntax: Convert. method(value) – Convert: the name of the class – method: converts value to specified data type – value: numeric data to be converted • Example – Dim sales As Integer = 4500 new. Sales As Double Convert. To. Double(sales) Dim new. Sales = Programming with Microsoft Visual Basic 2005, Third Edition 15
Using a Variable in an Arithmetic Expression • Data stored in variables can be used in calculations • Example 1 – Dim age As Integer ‘ Dim allocates memory for age = age + 1 ‘ A new value is assigned • Example 2 – Dim total. Amount. Due As Double = 250. 55 Me. x. Total. Label. Text = _ Convert. To. String(total. Amount. Due) – Line continuation character: underscore in line 2 Programming with Microsoft Visual Basic 2005, Third Edition 16
The Scope and Lifetime of a Variable • Scope: indicates where a variable can be used • Lifetime: indicates how long a variable can be used • Scope and lifetime determined by declaration site • Three types of scope – Block: variable used within a specific code block – Procedure: variable only used within a procedure – Module: variable used by all procedures in a form Programming with Microsoft Visual Basic 2005, Third Edition 17
The Scope and Lifetime of a Variable (continued) Figure 3 -14: Total Sales application’s code using a module-level variable Programming with Microsoft Visual Basic 2005, Third Edition 18
Static Variables • Static variable – Procedure level variable with extended lifetime – Remains in memory between procedure calls – Declare a variable using the Static keyword • Example: Static total. Sales As Decimal – Value in total. Sales persists between calls – During a current call, value may be altered • Static variables act like module-level variables – Difference: static variable has narrower scope Programming with Microsoft Visual Basic 2005, Third Edition 19
Named Constants • Named constant – Memory location inside the computer – Contents cannot be changed at runtime • Const statement: creates a named constant • Syntax: Const constantname As datatype = expression • Example: Const PI As Double = 3. 141593 Programming with Microsoft Visual Basic 2005, Third Edition 20
Option Explicit and Option Strict • Option Explicit On statement – Prevents you from using undeclared variables • Implicit type conversion – Converts right-side value to datatype of left side – Promotion: data expanded; e. g. , Integer to Decimal – Demotion: data truncated; e. g. , Decimal to Integer • Option Strict On statement – Suppresses implicit conversions Programming with Microsoft Visual Basic 2005, Third Edition 21
Option Explicit and Option Strict (continued) Figure 3 -19: Rules and examples of implicit type conversions Programming with Microsoft Visual Basic 2005, Third Edition 22
Option Explicit and Option Strict (continued) Figure 3 -20: Option statements entered in the General Declarations section Programming with Microsoft Visual Basic 2005, Third Edition 23
Summary – Lesson A • Declare a variable using {Dim | Private | Static} • Assignment statement: assigns value to a variable • Three levels of scope: block, procedure, module • Try. Parse () converts strings to numeric data • Avoid programming errors by using Option Explicit On and Option Strict On Programming with Microsoft Visual Basic 2005, Third Edition 24
Modifying the Skate-Away Sales Application Lesson B Objectives • Include a procedure-level and module-level variable in an application • Concatenate strings • Get user input using the Input. Box function • Include the Control. Chars. New. Line constant in code Programming with Microsoft Visual Basic 2005, Third Edition 25
Modifying the Skate-Away Sales Application Lesson B Objectives (continued) • Designate the default button for a form • Format numbers using the To. String method Programming with Microsoft Visual Basic 2005, Third Edition 26
Revising the Application’s Documents • Modifications needed – Display message, sales tax amount, salesperson – Calculate the sales tax • Revise TOE chart to reflect new tasks • Three controls are impacted – x. Calc. Button, Main. Form, x. Message. Label • Modify button’s Click event and form’s Load event Programming with Microsoft Visual Basic 2005, Third Edition 27
Modifying the Calculate Order Button’s Code • General strategy – Remove existing code from Click event procedure – Recode the procedure using variables in equations • Use Option Explicit On statement – Enforces full variable declaration • Use Option Strict On statement – Suppresses implicit type conversions Programming with Microsoft Visual Basic 2005, Third Edition 28
Modifying the Calculate Order Button’s Code (continued) Figure 3 -25: Revised pseudocode for the x. Calc. Button’s Click event procedure Programming with Microsoft Visual Basic 2005, Third Edition 29
Modifying the Calculate Order Button’s Code (continued) Figure 3 -29: Calculated amounts shown in the interface Programming with Microsoft Visual Basic 2005, Third Edition 30
Concatenating Strings • Concatenate: connect strings together • Concatenation operator: the ampersand (&) • Include a space before and after the & operator • Numbers after & operator are converted to strings Programming with Microsoft Visual Basic 2005, Third Edition 31
Concatenating Strings (continued) Figure 3 -30: Examples of string concatenation Programming with Microsoft Visual Basic 2005, Third Edition 32
The Input. Box Function • Input. Box function – Displays a dialog box and retrieves user input • Syntax: Input. Box(prompt[, title][, default. Response]) – prompt: the message to display inside dialog box – title: text to display in the dialog box’s title bar – default. Response: text you want displayed • Arguments are String literals, constants, or variables Programming with Microsoft Visual Basic 2005, Third Edition 33
The Input. Box Function (continued) Figure 3 -33: Example of a dialog box created by the Input. Box function Programming with Microsoft Visual Basic 2005, Third Edition 34
The Input. Box Function (continued) Figure 3 -36: Main. Form’s Load event procedure Programming with Microsoft Visual Basic 2005, Third Edition 35
The Controlchars. Newline Constant • Issues a carriage return followed by a line feed • Using the Control. Chars. New. Line constant – Type Control. Chars. New. Line at appropriate location Programming with Microsoft Visual Basic 2005, Third Edition 36
The Controlchars. Newline Constant (continued) Figure 3 -39: Control. Chars. New. Line constant added to the assignment statement Programming with Microsoft Visual Basic 2005, Third Edition 37
Designating a Default Button • Default button – Can be selected by pressing the Enter key – Button is not required to have the focus • The default button is typically the first button • Button’s deleting data should not be made default • Specifying the default button (if any) – Set form’s Accept. Button property to desired button Programming with Microsoft Visual Basic 2005, Third Edition 38
Using the To. String Method to Format Numbers • Formatting – Specifying decimal places and special characters • To. String method is replacing the Format function • Syntax: variablename. To. String(format. String) – variablename: name of a numeric variable – format. String: string specifying format you want to use • Form Axx consists of a format and precision specifier • Example: C 2 format. String converts 75. 312 to $75. 31 Programming with Microsoft Visual Basic 2005, Third Edition 39
Using the To. String Method to Format Numbers (continued) Figure 3 -46: Order form showing the formatted total price Programming with Microsoft Visual Basic 2005, Third Edition 40
Summary – Lesson B • Concatenation operator (&): used to link strings • Input. Box function: displays interactive dialog box • Use Control. Chars. New. Line to go to a new line • Set default button in form’s Accept. Button property • To. String method: formats number for string output Programming with Microsoft Visual Basic 2005, Third Edition 41
Modifying the Skate-Away Sales Application’s Code Lesson C Objectives • Include a static variable in code • Code the Text. Changed event procedure • Create a procedure that handles more than one event Programming with Microsoft Visual Basic 2005, Third Edition 42
Modifying the Code in the Main. Form’s Load and x. Calc. Button Click Procedures • Capability needed when each order is calculated – Order form to ask for the salesperson’s name • Revise TOE chart before implementing changes • Objects impacted: x. Calc. Button and Main. Form • Shift task of retrieving name to x. Calc. Button • Use a static variable to store salesperson’s name Programming with Microsoft Visual Basic 2005, Third Edition 43
Modifying the Code in the Main. Form’s Load and x. Calc. Button Click Procedures (continued) Figure 3 -51: Revised pseudocode for the Calculate Order button Programming with Microsoft Visual Basic 2005, Third Edition 44
Using a Static Variable • Static variable – Retains its value between procedure calls – Like a module-level variable with reduced scope • Syntax – Static variablename [As datatype] [= initialvalue] • Example of declaring a static variable – Static sales. Person As String = String. Empty Programming with Microsoft Visual Basic 2005, Third Edition 45
Coding the Text. Changed Event Procedure • Control’s Text. Changed event – Occurs when the Text property value changes • Triggering events – The user enters data into the control – Code assigns data to the control’s Text property • Example – A change is made to the number of items ordered Programming with Microsoft Visual Basic 2005, Third Edition 46
Associating a Procedure with Different Objects and Events • The keyword Handles – Appears in a procedure header – Indicates object and event associated with procedure • Procedures can relate to multiple objects and events • Associating procedures with extra objects and events – Go to the Handles section of the procedure header – List each object and event, separated by commas Programming with Microsoft Visual Basic 2005, Third Edition 47
Associating a Procedure with Different Objects and Events (continued) Figure 3 -56: Completed Clear. Controls procedure Programming with Microsoft Visual Basic 2005, Third Edition 48
Summary – Lesson C • Static variables retain their value between calls • Text. Changed event procedure responds to change in value of control’s Text Property • Handles clause determines when Text. Changed event procedure is invoked • To create a procedure for more than one object or event, list each object and event after Handles Programming with Microsoft Visual Basic 2005, Third Edition 49
- Slides: 49