Download presentation
Presentation is loading. Please wait.
Published byAllan Woodard Modified over 9 years ago
1
Chapter 3: Using Variables and Constants Programming with Microsoft Visual Basic 2005, Third Edition
2
2 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 TryParse method Convert numeric data to a different data type using the Convert class methods
3
3 Programming with Microsoft Visual Basic 2005, Third Edition 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
4
4 Programming with Microsoft Visual Basic 2005, Third Edition Previewing the Completed Application Previewing the Skate-Away Sales application –Access the Run command on the Start menu –Browse to the VB2005\Chap03 folder –Open the SkateAway (SkateAway.exe) file –View the completed order form Completed application resembles Chapter 2 version
5
5 Programming with Microsoft Visual Basic 2005, Third Edition Previewing the Completed Application (continued) Figure 3-1: Name Entry dialog box
6
6 Programming with Microsoft Visual Basic 2005, Third Edition 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
7
7 Programming with Microsoft Visual Basic 2005, Third Edition 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.2E6 Floating-point variables: Single, Double
8
8 Programming with Microsoft Visual Basic 2005, Third Edition 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
9
9 Programming with Microsoft Visual Basic 2005, Third Edition 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., salesAmount Certain rules must be followed –Example: a name begins with a letter or underscore
10
10 Programming with Microsoft Visual Basic 2005, Third Edition Selecting a Name for a Variable (continued) Figure 3-4: Rules for variable names along with examples of valid and invalid names
11
11 Programming with Microsoft Visual Basic 2005, Third Edition Declaring a Variable Declaration statement –Used to declare, or create, a variable Syntax: {Dim | Private | Static} variablename [As datatype][= initialvalue] Examples –Dim hoursWorked As Double ‘note: no initial value –Dim isDataOk As Boolean = True ‘ variable initialized –Dim message As String = “Good Morning”
12
12 Programming with Microsoft Visual Basic 2005, Third Edition Assigning Data to an Existing Variable Assignment statement –Assigns a value to a variable at runtime Syntax: variablename = value –Example: quantityOrdered = 500 Literal constant: data item that does not change –Example: the string “Mary” Literal type character: changes type of a literal –Example: sales = 2356R ‘ integer cast to Double
13
13 Programming with Microsoft Visual Basic 2005, Third Edition Assigning Data to an Existing Variable (continued) Figure 3-7: Literal type characters
14
14 Programming with Microsoft Visual Basic 2005, Third Edition The TryParse Method Syntax: dataType.TryParse(string, variable) –dataType: numeric data type, such as Integer –TryParse method is a member of dataType class –string argument: string to convert to a number –variable argument: names numeric storage unit Example –Dim sales As Decimal Decimal.TryParse(Me.xSalesTextBox.Text, sales)
15
15 Programming with Microsoft Visual Basic 2005, Third Edition 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 Dim newSales As Double newSales = Convert.ToDouble(sales)
16
16 Programming with Microsoft Visual Basic 2005, Third Edition 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 = age + 1 ‘ A new value is assigned Example 2 –Dim totalAmountDue As Double = 250.55 Me.xTotalLabel.Text = _ Convert.ToString(totalAmountDue) –Line continuation character: underscore in line 2
17
17 Programming with Microsoft Visual Basic 2005, Third Edition 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
18
18 Programming with Microsoft Visual Basic 2005, Third Edition The Scope and Lifetime of a Variable (continued) Figure 3-14: Total Sales application’s code using a module-level variable
19
19 Programming with Microsoft Visual Basic 2005, Third Edition 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 totalSales As Decimal –Value in totalSales persists between calls –During a current call, value may be altered Static variables act like module-level variables –Difference: static variable has narrower scope
20
20 Programming with Microsoft Visual Basic 2005, Third Edition 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
21
21 Programming with Microsoft Visual Basic 2005, Third Edition 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
22
22 Programming with Microsoft Visual Basic 2005, Third Edition Option Explicit and Option Strict (continued) Figure 3-19: Rules and examples of implicit type conversions
23
23 Programming with Microsoft Visual Basic 2005, Third Edition Option Explicit and Option Strict (continued) Figure 3-20: Option statements entered in the General Declarations section
24
24 Programming with Microsoft Visual Basic 2005, Third Edition Summary – Lesson A Declare a variable using {Dim | Private | Static} Assignment statement: assigns value to a variable Three levels of scope: block, procedure, module TryParse () converts strings to numeric data Avoid programming errors by using Option Explicit On and Option Strict On
25
25 Programming with Microsoft Visual Basic 2005, Third Edition 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 InputBox function Include the ControlChars.NewLine constant in code
26
26 Programming with Microsoft Visual Basic 2005, Third Edition Modifying the Skate-Away Sales Application Lesson B Objectives (continued) Designate the default button for a form Format numbers using the ToString method
27
27 Programming with Microsoft Visual Basic 2005, Third Edition 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 –xCalcButton, MainForm, xMessageLabel Modify button’s Click event and form’s Load event
28
28 Programming with Microsoft Visual Basic 2005, Third Edition 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
29
29 Programming with Microsoft Visual Basic 2005, Third Edition Modifying the Calculate Order Button’s Code (continued) Figure 3-25: Revised pseudocode for the xCalcButton’s Click event procedure
30
30 Programming with Microsoft Visual Basic 2005, Third Edition Modifying the Calculate Order Button’s Code (continued) Figure 3-29: Calculated amounts shown in the interface
31
31 Programming with Microsoft Visual Basic 2005, Third Edition 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
32
32 Programming with Microsoft Visual Basic 2005, Third Edition Concatenating Strings (continued) Figure 3-30: Examples of string concatenation
33
33 Programming with Microsoft Visual Basic 2005, Third Edition The InputBox Function InputBox function –Displays a dialog box and retrieves user input Syntax: InputBox(prompt[, title][, defaultResponse]) –prompt: the message to display inside dialog box –title: text to display in the dialog box’s title bar –defaultResponse: text you want displayed Arguments are String literals, constants, or variables
34
34 Programming with Microsoft Visual Basic 2005, Third Edition The InputBox Function (continued) Figure 3-33: Example of a dialog box created by the InputBox function
35
35 Programming with Microsoft Visual Basic 2005, Third Edition The InputBox Function (continued) Figure 3-36: MainForm’s Load event procedure
36
36 Programming with Microsoft Visual Basic 2005, Third Edition The Controlchars.Newline Constant Issues a carriage return followed by a line feed Using the ControlChars.NewLine constant –Type ControlChars.NewLine at appropriate location
37
37 Programming with Microsoft Visual Basic 2005, Third Edition The Controlchars.Newline Constant (continued) Figure 3-39: ControlChars.NewLine constant added to the assignment statement
38
38 Programming with Microsoft Visual Basic 2005, Third Edition 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 AcceptButton property to desired button
39
39 Programming with Microsoft Visual Basic 2005, Third Edition Using the ToString Method to Format Numbers Formatting –Specifying decimal places and special characters ToString method is replacing the Format function Syntax: variablename.ToString(formatString) –variablename: name of a numeric variable –formatString: string specifying format you want to use Form Axx consists of a format and precision specifier Example: C2 formatString converts 75.312 to $75.31
40
40 Programming with Microsoft Visual Basic 2005, Third Edition Using the ToString Method to Format Numbers (continued) Figure 3-46: Order form showing the formatted total price
41
41 Programming with Microsoft Visual Basic 2005, Third Edition Summary – Lesson B Concatenation operator (&): used to link strings InputBox function: displays interactive dialog box Use ControlChars.NewLine to go to a new line Set default button in form’s AcceptButton property ToString method: formats number for string output
42
42 Programming with Microsoft Visual Basic 2005, Third Edition Modifying the Skate-Away Sales Application’s Code Lesson C Objectives Include a static variable in code Code the TextChanged event procedure Create a procedure that handles more than one event
43
43 Programming with Microsoft Visual Basic 2005, Third Edition Modifying the Code in the MainForm’s Load and xCalcButton 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: xCalcButton and MainForm Shift task of retrieving name to xCalcButton Use a static variable to store salesperson’s name
44
44 Programming with Microsoft Visual Basic 2005, Third Edition Modifying the Code in the MainForm’s Load and xCalcButton Click Procedures (continued) Figure 3-51: Revised pseudocode for the Calculate Order button
45
45 Programming with Microsoft Visual Basic 2005, Third Edition 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 salesPerson As String = String.Empty
46
46 Programming with Microsoft Visual Basic 2005, Third Edition Coding the TextChanged Event Procedure Control’s TextChanged 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
47
47 Programming with Microsoft Visual Basic 2005, Third Edition 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
48
48 Programming with Microsoft Visual Basic 2005, Third Edition Associating a Procedure with Different Objects and Events (continued) Figure 3-56: Completed ClearControls procedure
49
49 Programming with Microsoft Visual Basic 2005, Third Edition Summary – Lesson C Static variables retain their value between calls TextChanged event procedure responds to change in value of control’s Text Property Handles clause determines when TextChanged event procedure is invoked To create a procedure for more than one object or event, list each object and event after Handles
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.