Download presentation
Presentation is loading. Please wait.
Published bySheena Murphy Modified over 8 years ago
1
Programming with Microsoft Visual Basic 2012 Chapter 3: Using Variables and Constants
2
Previewing the Modified Play It Again Movies Application Play It Again Movies application –New screen for salesclerk’s name –Sales tax added to order Programming with Microsoft Visual Basic 20122 Figure 3-2 Completed sales receipt Figure 3-1 Name Entry dialog box
3
Lesson A Objectives After studying Lesson A, you should be able to: Declare variables and named constants Assign data to an existing variable Convert string data to a numeric data type using TryParse method Convert numeric data to a different data type using Convert class methods Explain the scope and lifetime of variables and named constants Explain the purpose of Option Explicit, Option Infer, and Option Strict Programming with Microsoft Visual Basic 20123
4
Controls and variables temporarily store data Variable –A temporary storage location in main memory –Specified by data type, name, scope, and lifetime Reasons to use variables –To hold information that is not stored in a control on the form –To allow for more precise treatment of numeric data –To enable code to run more efficiently Programming with Microsoft Visual Basic 20124 Using Variables to Store Information
5
Using Variables to Store Information (cont.) Programming with Microsoft Visual Basic 20125 Selecting a Data Type for a Variable Data type –Specifies the type of data a variable can store –Provides a class template for creating variables Unicode –A universal ( 通用的 ) coding scheme for characters –Assigns a unique numeric value to each character in the written languages of the world
6
Basic Data Types in Visual Basic Programming with Microsoft Visual Basic 20126
7
The textbook uses: –The Integer data type for all integers –Either the Decimal or Double data type for numbers containing decimal places or numbers used in calculations –The String data type for text or numbers not used in calculations –The Boolean data type for Boolean values Programming with Microsoft Visual Basic 20127 Using Variables to Store Information (cont.)
8
Rules for Naming Variables Programming with Microsoft Visual Basic 20128 Selecting a Name for a Variable –Names must begin with a letter or underscore –Names can contain only letters, numbers, or underscores No punctuation, special characters, or spaces are allowed –The recommended length for a name variable is 32 characters –Variable names cannot be reserved words (such as Sub or Double) Figure 3-4 3-character IDs and examples in Hungarian notation
9
Valid and Invalid Variable Names Valid names: –intFeb_Income –decSales2014 –dblEastRegion –strName Invalid Names: –4thQuarter The name must begin with a letter or underscore –dblWest Region The name cannot contain a space –strFirst.Name The name cannot contain punctuation –decSales$East The name cannot contain a special character Programming with Microsoft Visual Basic 20129
10
Variable Declaration Declaring a Variable Declaration statement –Used to declare (create) a variable and reserve space in memory for it If no initial value is given to a variable when declaring it, the computer stores a default value –Numeric variables are set to 0 –Boolean variables are set to False –Object and String variables are set to Nothing –Date variables are set to 1/1/0001 12:00:00AM Programming with Microsoft Visual Basic 201210
11
Programming with Microsoft Visual Basic 201211 Variable Declaration Statement Figure 3-6 Syntax and examples of a variable declaration statement
12
Assigning Data to an Existing Variable Programming with Microsoft Visual Basic 201212 Assignment statement –Assigns a value to a variable at run time –Syntax: variablename = expression –An expression may include literal constants, object properties, variables, keywords, and arithmetic operators Literal constant –A data item whose value does not change while the application is running –Example: The string “Mary” Literal type character –Forces a literal constant to change its data type
13
Assigning Data to an Existing Variable Programming with Microsoft Visual Basic 2012 13 Figure 3-7 Syntax and examples of assigning a value to a variable during run time
14
Assigning Data to an Existing Variable (cont.) Programming with Microsoft Visual Basic 201214 The TryParse Method Converts a string to a number Is preferred over Val –Allows the programmer to specify the data type –Val only returns a Double number Arguments –dataType: A numeric data type, such as Integer –String: A string to be converted –Variable: A variable that receives the numeric value
15
TryParse Method Programming with Microsoft Visual Basic 201215 Figure 3-9 Basic syntax and examples of the TryParse method
16
TryParse Method Programming with Microsoft Visual Basic 201216 Figure 3-10 Results of the TryParse method for the Double, Decimal and Integer data types
17
Convert Class Programming with Microsoft Visual Basic 2012 17 The Convert Class Can be used to convert a number from one type to another Methods include –ToDecimal –ToDouble –ToInt32 –ToString TryParse –For converting strings to numeric data types –Will not produce an error if the conversion fails
18
Convert Class Programming with Microsoft Visual Basic 2012 18 Figure 3-11 Syntax and examples of the Convert class methods
19
The Scope and Lifetime of a Variable Programming with Microsoft Visual Basic 201219 Scope –Indicates where a variable can be used Lifetime –How long a variable remains in memory Scope and lifetime are determined by where a variable is declared: either the General Declarations section or the form’s Declaration section Three types of scope: –Class: The variable can be used by all procedures in a form –Procedure: The variable can be used within a procedure –Block: The variable can be used within a specific code block
20
The Scope and Lifetime of a Variable (cont.) Programming with Microsoft Visual Basic 201220 Variables with Procedure Scope –Can be used only by that procedure –Declared at the beginning of the procedure –Removed from memory when the procedure ends –Declared using the Dim keyword Most variables used in this course will be procedure- level variables
21
Lifetime of a Variable Programming with Microsoft Visual Basic 201221 Figure 3-13 Click event procedures using procedure-level variables
22
The Scope and Lifetime of a Variable Programming with Microsoft Visual Basic 201222 Variables with Class Scope –Can be used by all procedures in the form –Declared in the form’s Declarations section –Will remain in memory until the application ends –Declared using the Private keyword
23
Class-Level and Procedure-Level Variables Programming with Microsoft Visual Basic 201223
24
Static Variables Programming with Microsoft Visual Basic 201224 Static variable –A procedure-level variable with an extended lifetime Remains in memory between procedure calls Retains its value even when the procedure ends –Static keyword Used to declare a static variable –Static variables act like class-level variables but have narrower scope They can only be used by the procedure in which they are declared
25
Static Variables (cont.) Programming with Microsoft Visual Basic 201225 Figure 3-19 Total Scores application’s code using a static variable
26
Named Constants Programming with Microsoft Visual Basic 201226 Named constant –A memory location inside the computer whose contents cannot be changed at run time Const statement –Creates named constant –Stores value of expression in a named constant –expression: Can be a literal constant, another named constant, or an arithmetic operator –Cannot contain a variable or method
27
Named Constants (cont.) Programming with Microsoft Visual Basic 201227 Figure 3-20 Syntax and examples of the Const statement
28
Option Statements Programming with Microsoft Visual Basic 201228 Option Explicit On Prevent you from using undeclared variables Option Infer Off Ensures that every variable is declared with a data type Option Strict Off/On Implicit type conversion –Converts the right-side value to the data type on the left side Promotion –Data is converted to a greater precision number (e.g., Integer to Decimal) Demotion –Data is truncated (e.g., Decimal to Integer) –Data loss can occur when demotion occurs
29
Option Statements (cont.) Programming with Microsoft Visual Basic 201229 Option Strict Off/On –Allows/Disallows implicit conversions –Type conversion rules are applied when this option is on
30
Example of Option Statements Programming with Microsoft Visual Basic 201230 Figure 3-25 Option statements entered in the General Declarations section
31
Programming with Microsoft Visual Basic 201231 Lesson A Summary Declare a variable using {Dim | Private | Static} An assignment statement assigns a value to a variable Three levels of variable scope: block, procedure, class The TryParse method converts strings to numeric data Use Const to declare a named constant Avoid programming errors by using Option Explicit On, Option Infer Off, and Option Strict On
32
Lesson B Objectives After studying Lesson B, you should be able to: Include procedure-level and class-level variables in an application Concatenate strings Get user input using the InputBox function Include the ControlChars.NewLine constant in code Designate the default button for a form Format numbers using the ToString method Programming with Microsoft Visual Basic 201232
33
Programming with Microsoft Visual Basic 201233 Modifying the Play It Again Movies Application Figure 3-26 Revised TOE chart for the Play It Again Movies application Modifications needed – Calculate and display the sales tax – Display salesperson’s name Revise the TOE chart to reflect the new tasks You must modify btnCalc button’s Click event and the form’s Load event
34
Modifying the Play It Again Movies Application (cont.) Programming with Microsoft Visual Basic 201234 Figure 3-27 Modified user interface for the Play It Again Movies application
35
Programming with Microsoft Visual Basic 201235 Modifying the Calculate Button’s Code General strategy –Remove the existing code from the Click event procedure –Re-code the procedure using variables in equations Use the Option Explicit On statement –Enforces full variable declaration Use the Option Infer Off statement –Ensures that variables are declared with data types Use the Option Strict On statement –Suppresses implicit type conversions
36
Option Strict On Disallows Implicit Type Conversions Programming with Microsoft Visual Basic 201236 Figure 3-29 Lines to delete from the procedure Figure 3-28 A jagged blue line indicates a syntax error
37
Modifying the Calculate Button’s Code (Using Variables in Equations) Programming with Microsoft Visual Basic 201237 Figure 3-30 Revised pseudocode and flowchart for the btnCalc control’s Click event procedure
38
Modifying the Calculate Button’s Code (cont.) Programming with Microsoft Visual Basic 201238 Figure 3-31 List of named constants and variables Figure 3-32 Const and Dim statements entered in the procedure
39
Modifying the Calculate Button’s Code (cont.) Programming with Microsoft Visual Basic 201239 Figure 3-33 Code entered in the btnCalc control’s Click event procedure Figure 3-34 Calculated amounts shown in the interface 練習 p. 150~153
40
Programming with Microsoft Visual Basic 201240 Concatenating Strings Concatenate strings –To connect strings together Concatenation operator –The ampersand (&) –Include a space before and after the ampersand Numeric values used with the & operator are converted to strings Figure 3-35 Examples of string concatenation
41
Programming with Microsoft Visual Basic 201241 Concatenating Strings (cont.) Figure 3-37 Concatenated strings displayed in the lblMessage control Figure 3-36 String concatenation included in the assignment statement Old program
42
Programming with Microsoft Visual Basic 201242 The InputBox Function InputBox function –Displays an input dialog box and retrieves user input Arguments –prompt: Contains the message to display inside the dialog box –title: Controls the text that appears in the dialog box’s title bar –defaultResponse: Controls the text that appears in the input field The returned value most often assigned to String variable Syntax & example
43
Programming with Microsoft Visual Basic 201243 The InputBox Function (cont.) Figure 3-38 Example of an input dialog box Figure 3-39 Basic syntax and examples of the InputBox function
44
Programming with Microsoft Visual Basic 201244 The InputBox Function (cont.) Figure 3-41 frmMain Load event procedure Figure 3-42 Dialog box created by the InputBox function
45
Programming with Microsoft Visual Basic 201245 The ControlChars.Newline Constant ControlChars.NewLine constant –Advances text insertion point to the next line in a control –Also used to advance text insertion point to the next line in file or on the printer To use, type ControlChars.NewLine in the appropriate location –Can be used with string concatenation Line continuation character (_) –Used to break up a long line of code into two or more lines
46
Programming with Microsoft Visual Basic 201246 The ControlChars.Newline Constant (cont.) Figure 3-43 Modified assignment statement Figure 3-45 Salesclerk’s name shown on the sales receipt 練習 p. 157~159
47
Programming with Microsoft Visual Basic 201247 Designating a Default Button Default button –Activated by pressing the Enter key –Not required to have the focus –Only one per form The default button should be the button used most often by the user –Except if button’s task is destructive and irreversible, such as deleting data Set the form’s AcceptButton property to the button name
48
Programming with Microsoft Visual Basic 201248 Using the ToString Method to Format Numbers Formatting –Specifying decimal places and special characters to display The ToString method replaces the Format function Syntax: variablename.ToString(formatString) –variablename: The name of a numeric variable –formatString: The string specifying the format you want to use formatString must take the form Axx, where A is the format specifier and xx is the precision specifier
49
Programming with Microsoft Visual Basic 201249 Using the ToString Method to Format Numbers (Cont.) Figure 3-46 Syntax and examples of the ToString method
50
Programming with Microsoft Visual Basic 201250 Using the ToString Method to Format Numbers (Cont.) Figure 3-48 Play It Again Movies application’s code at the end of Lesson B 練習 p. 160, 162
51
Programming with Microsoft Visual Basic 201251 Lesson B Summary The concatenation operator (&) is used to link strings The InputBox function displays an interactive dialog box Use ControlChars.NewLine to move the insertion point to a new line Set the default button in the form’s AcceptButton property The ToString method formats a number for string output
52
Lesson C Objectives After studying Lesson C, you should be able to: Include a static variable in code Code the TextChanged event procedure Create a procedure that handles more than one event Programming with Microsoft Visual Basic 201252
53
Modifying the Load and Click Event Procedures Programming with Microsoft Visual Basic 201253 Figure 3-51 Revised TOE Chart for the Play It Again Movies application in Lesson C
54
Modifying the Load and Click Event Procedures (Cont.) Programming with Microsoft Visual Basic 201254 Figure 3-52 Revised pseudocode for the Calculate button in Lesson C
55
Coding the TextChanged Event Procedure TextChanged event –Occurs when the Text property value of a control changes Can occur when: –The user enters data into the control –The 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 201255
56
Coding the TextChanged Event Procedure (Cont.) Associating a Procedure with Different Objects and Events Handles clause –Appears in an event procedure’s header –Indicates the object and event associated with the procedure You can associate an event procedure with more than one object and/or event –In the Handles section of procedure header, list each object and event separated by commas –Procedure names are entered in Pascal case Capitalize the first letter in the name and the first letter of each subsequent word in the name Programming with Microsoft Visual Basic 201256
57
Coding the TextChanged Event Procedure (cont.) Programming with Microsoft Visual Basic 201257 Figure 3-53 TextChanged event procedure associated with the txtDvds control Figure 3-54 Completed ClearLabels procedure 練習 p. 172~ 176
58
Programming with Microsoft Visual Basic 201258 Lesson C Summary The TextChanged event procedure responds to a change in the value of a control’s Text Property The Handles clause determines which objects and events are associated with the event procedure To create a procedure for more than one object or event, list each object and event after the Handles keyword
Similar presentations
© 2024 SlidePlayer.com Inc.
All rights reserved.