Microsoft Visual Basic 2015: Reloaded Sixth Edition Chapter Three Memory Locations and Calculations
Objectives After studying this chapter, you should be able to: Declare variables and named constants Assign data to an existing variable Convert data to the appropriate type using the TryParse method, Convert class methods, and a literal type character Write and evaluate arithmetic expressions Understand the scope and lifetime of variables and named constant 2
Objectives (cont d.) Understand the purpose of the Option statements Use a TOE chart, pseudocode, and a flowchart to code an application Format an application s numeric output Clear the contents of a control s Text property during run time Send the focus to a control during run time Explain the different types of program errors 3
Internal Memory Figure 3-1: Illustration of shoe boxes and memory locations Memory locations can also be reserved (declared) by a programmer for use in a program The data type indicates the type of data for example, numeric or string the memory location will store 4
Variables A variable is a computer memory location that a programmer uses to temporarily store data while an application is running Figure 3-2: How to name a variable 5
Variables (cont d.) Figure 3-3: Basic data types in Visual Basic 6
Variables (cont d.) Integer, Long, or Short data types store integers, which are positive or negative numbers and have no decimal places Decimal, Double, or Single data types store real numbers, which are numbers that contain a decimal place Char data type can store one Unicode character String data type can store from zero to approximately two billion Unicode characters Boolean data type can store Boolean values (True or False) Date data type can store date and time information Object data type can store any type of data 7
Variables (cont d.) Declaring a Variable in Code The declaration statement tells the computer to set aside a small section of its internal memory, and it allows the programmer to refer to the section by the variable s name The {Dim Private Static} portion of the syntax indicates that you can select only one of the keywords appearing within the braces Figure 3-4: How to declare a variable 8
Assigning Data to an Existing Variable A literal constant An item of data whose value does not change during run time A literal type character Forces a literal constant to assume a data type other than the one its form indicates 9
Assigning Data to an Existing Variable 10 Figure 3-5: How to assign a value to an existing variable
Assigning Data to an Existing Variable (cont d.) Using the TryParse Method Each data type in Visual Basic is a class Most classes have one or more methods that perform a specific task for the class All of the Visual Basic numeric data types (such as Double, Decimal, or Integer) have a TryParse method The TryParse method s task is to convert a string to a particular numeric data type 11
Assigning Data to an Existing Variable (cont d.) 12 Figure 3-6: How to use the basic syntax of the TryParse method
Assigning Data to an Existing Variable (cont d.) The dot member access operator in the syntax indicates that the TryParse method is a member of the datatype class The TryParse method parses its string argument to determine whether the string can be converted to a number of the specified data type An empty string, also referred to as a zero-length string, is a set of quotation marks with nothing between them 13
Assigning Data to an Existing Variable (cont d.) Figure 3-7: Results of the TryParse method for the Double, Decimal, and Integer data types 14
Assigning Data to an Existing Variable (cont d.) Using the Convert Class Methods At times, you may need to convert a number (rather than a string) from one data type to another use one of the methods defined in the Convert class The syntax for includes the dot member access operator which indicates that the method is a member of the Convert class In most cases, the method s value argument is a numeric value that you want converted either to the String data type or to a different numeric data type 15
Assigning Data to an Existing Variable (cont d.) 16 Figure 3-8: How to use the Convert class methods
Arithmetic Expressions Figure 3-9: Most commonly used arithmetic operators The integer division operator is used to divide two integers and then return the result as an integer The modulus operator (sometimes referred to as the remainder operator) is also used to divide two numbers, but the numbers do not have to be integers After dividing the numbers, the modulus operator returns the remainder of the division 17
Arithmetic Expressions (cont d.) Figure 3-10: How to use the integer division and Mod operators 18
Arithmetic Expressions (cont d.) Figure 3-11: How to evaluate expressions containing operators with the same precedence 19
Arithmetic Expressions (cont d.) Figure 3-12: How to assign the result of an arithmetic expression to a variable (continues) 20
Arithmetic Expressions (cont d.) (continued) Figure 3-12: How to assign the result of an arithmetic expression to a variable 21
Arithmetic Expressions (cont d.) Arithmetic Assignment Operators Use the arithmetic assignment operators to abbreviate an assignment statement that contains an arithmetic operator variablename = variablename arithmeticoperator value age = age + 1 Use the addition assignment operator (+=) to abbreviate the statement above as follows: age += 1 Both statements tell the computer to add the number 1 to the contents of the age variable and then store the result in the variable 22
Arithmetic Expressions (cont d.) 23 Figure 3-13: How to use the arithmetic assignment operators (continues)
Arithmetic Expressions (cont d.) Figure 3-13: How to use the arithmetic assignment operators 24
Scope and Lifetime A variable s scope indicates where the variable can be used in an application s code A variable s lifetime indicates how long the variable remains in the computer s internal memory Variables can have class scope, procedure scope, or block scope Variables declared in a form s Declarations section have class scope Variables declared in a procedure have procedure scope or block depending on where in the procedure they are declared 25
Scope and Lifetime (cont d.) Programmers use comments to document a procedure s purpose and to explain various sections of a procedure s code Figure 3-14: Variables declared in the form s Declarations section and calcbutton_click procedure 26
Scope and Lifetime (cont d.) Variables with Procedure Scope Variables declared in a procedure are called procedure-level variables Procedure-level variables: Have procedure scope because they can be used only within the procedure in which it is declared Are typically declared at the beginning of a procedure, and remain in the computer s internal memory only while the procedure is running Are declared using the Dim keyword 27
Scope and Lifetime (cont d.) Figure 3-15: Sample run of the Discount Calculator application 28
Scope and Lifetime (cont d.) Figure 3-16: Click event procedures using procedure-level variables (continues) 29
Scope and Lifetime (cont d.) (continued) 30 Figure 3-16: Click event procedures using procedure-level variables
Scope and Lifetime (cont d.) In an application you can use the same name to declare a variable in more than one procedure When this is done, each procedure creates its own variable when the procedure is invoked Each procedure also destroys its own variable when the procedure ends Each variable is located in a different section in the computer s internal memory and each is an independent entity 31
Scope and Lifetime (cont d.) Figure 3-17: Illustration of shoe boxes and variables 32
Scope and Lifetime (cont d.) Variables with Class Scope A class-level variable has class scope Class-level variables: Are declared in the form s Declarations section, which begins with the Public Class clause and ends with the End Class clause Retain their values and remain in the computer s internal memory until the application ends Are declared using the Private keyword 33
Scope and Lifetime (cont d.) Figure 3-18: Sample run of the Total Calories application 34 Figure 3-19: Total Calories application s code using a class-level variable
Scope and Lifetime (cont d.) Static Variables Variables are declared using the Dim, Private, or Static keywords A static variable is a procedure-level variable that remains in memory, and also retains its value, even when the procedure in which it is declared ends Like a class-level variable, a static variable is not removed from the computer s internal memory until the application ends Unlike a class-level variable, which can be used by all the procedures in a form, a static variable can be used only by the procedure in which it is declared 35
Scope and Lifetime (cont d.) Figure 3-20: Total Calories application s code using a static variable 36
Named Constants A named constant is a computer memory location whose contents cannot be changed during run time Declare a named constant using the Const statement Named constants make code more self-documenting and easier to modify because they allow a programmer to use meaningful words in place of values that are less clear 37
Scope and Lifetime (cont d.) 38 Figure 3-21: How to declare a named constant
Option Statements Option Explicit and Option Infer Every variable should appear in a declaration statement, such as a Dim, Private, or Static statement Option Strict If the value s data type does not match the memory location s data type, implicit type conversion occurs to convert the value to fit the memory location When a value is converted from one data type to another data type that can store either larger numbers or numbers with greater precision, the value is said to be promoted 39
Option Statements (cont d.) When a value is converted from one data type to another data type that can store only smaller numbers or numbers with less precision, the value is said to be demoted 40 Figure 3-22: How to use the type conversion rules with Option Strict On
Option Statements (cont d.) Figure 3-23: Option statements entered in the General Declarations section 41
Completing the Say Cheese! Company s Application 42 Figure 3-24: Interface from Chapter 2
Completing the Say Cheese! Company s Application (cont d.) Figure 3-25: TOE chart from Chapter 2 43
Completing the Say Cheese! Company s Application (cont d.) Using Pseudocode to Plan a Procedure Pseudocode uses short phrases to describe the steps a procedure must take to accomplish its goal Figure 3-26: Pseudocode for the Say Cheese! company s application 44
Completing the Say Cheese! Company s Application (cont d.) Using a Flowchart to Plan a Procedure A flowchart uses standardized symbols to show the steps a procedure must follow to reach its goal Flowcharts contain at least three different symbols: The oval symbol is called the start/stop symbol The rectangles are called process symbols The parallelogram in a flowchart is called the input/output symbol and is used to represent input tasks The lines connecting the symbols in a flowchart are called flowlines 45
Completing the Say Cheese! Company s Application (cont d.) Figure 3-27: Flowcharts for the Say Cheese! Company s application 46
Coding the calcbutton s Click Event Procedure Figure 3-28: Pseudocode for the calcbutton_click procedure Figure 3-29: Memory locations for the calcbutton_click procedure 47
Coding the calcbutton s Click Event Procedure (cont d.) Figure 3-30: Declaration statements entered in the procedure 48 Figure 3-31: TryParse methods entered in the procedure
Coding the calcbutton s Click Event Procedure (cont d.) Figure 3-32: Calculation statements entered in the procedure 49 Figure 3-33: Display statements and a sample run
Coding the calcbutton s Click Event Procedure (cont d.) Formatting Numeric Output Specifying the number of decimal places and the special characters to display in a number is called formatting The ToString method converts a numeric value to a string Places a copy of the variable s or named constant s contents in a temporary memory location Then converts the copy to a string 50
Coding the calcbutton s Click Event Procedure (cont d.) Figure 3-34: How to format a number using the ToString method (continues) 51
Coding the calcbutton s Click Event Procedure (cont d.) 52 Figure 3-34: How to format a number using the ToString method
Coding the calcbutton s Click Event Procedure (cont d.) Figure 3-35: Modified calcbutton_click procedure 53
Coding the clearbutton s Click Event Procedure Figure 3-36: Pseudocode for the clearbutton_click procedure 54
Coding the clearbutton s Click Event Procedure (cont d.) Two ways to clear the Text property of a control: Assign an empty (or zero-length) string to the property Assign the value String.Empty to the property Figure 3-37: How to clear the Text property of a control 55
Coding the clearbutton s Click Event Procedure (cont d.) The Focus method sends the focus to the nametextbox Figure 3-38: How to send the focus to a control Figure 3-39: clearbutton_click procedure 56
Coding the exitbutton_click and printbutton_click Procedures Procedure Figure 3-40: Say Cheese! company s program (continues) 57
Coding the exitbutton_click and printbutton_click Procedures Procedure (cont d.) 58 Figure 3-40: Say Cheese! company s program
Testing and Debugging the Application Applications must be tested to verify that the code works correctly A logic error can occur for a variety of reasons A run time error causes the application to end abruptly Your sample input data should include both valid and invalid data Valid data is data that the application is expecting the user to enter Invalid data is data that the application is not expecting the user to enter 59
Programming Tutorial 1 Figure 3-41: TOE chart for the Basketball Score application Figure 3-50: Sample run of the Basketball Score application 60
Programming Tutorial 2 Figure 3-54: MainForm for the Alligator Inc. application 61 Figure 3-58: Sample run of the Alligator Inc. application
Programming Example Figure 3-63: Sample run of the VitaDrink Company application 62
Summary Each memory location in the computer s internal memory can store only one item at a time Variables and named constants are computer memory locations that the programmer uses to store data while an application is running All variables and named constants have a name, data type, initial value, scope, and lifetime The name assigned to a memory location (variable or named constant) should describe the memory location s contents 63
Summary (cont'd.) A variable declared in a procedure has procedure scope, and its declaration statement begins with either the keyword Dim or the keyword Static A variable declared in a form s Declarations section has class scope, and its declaration statement begins with the keyword Private You can use an assignment statement to assign a value to an existing variable during run time A literal constant is an item of data whose value does not change during run time 64
Summary (cont'd.) You can use the D literal type character to force a Double literal constant (number) to assume the Decimal data type String literal constants are enclosed in quotation marks ("") You can use the TryParse method to convert a string to a number The Convert class contains methods that convert values to a specified data type 65
Summary (cont'd.) When an arithmetic expression contains the name of a memory location the computer uses the value stored inside the memory location to process the expression You can use the arithmetic assignment operators to abbreviate some assignment statements A procedure-level memory location can be used only by the procedure in which it is declared Procedure-level variables declared with the Dim keyword are removed from memory when the procedure ends 66
Summary (cont'd.) A class-level memory location can be used by all the procedures in the form, including the procedures associated with the controls contained on the form Programmers use comments to internally document an application s code. Comments begin with an apostrophe (') Use the Const statement to declare a named constant The Option Explicit On statement tells the Code Editor to flag the name of an undeclared variable in the code 67 Microsoft Visual Basic 2015: Reloaded, Sixth Edit
Summary (cont'd.) The Option Infer Off statement tells the Code Editor to warn you if a declaration statement does not contain a data type The Option Strict On statement tells the computer not to perform any implicit type conversions that may lead to a loss of data Programmers commonly use either pseudocode (short phrases) or a flowchart (standardized symbols) when planning a procedure s code 68
Summary (cont'd.) Use the ToString method to format an application s numeric output so that it displays special characters (such as dollar signs and commas) and a specified number of decimal places While an application is running, you can remove the contents of a text box or label by assigning either the empty string ("") or the String.Empty value to the control s Text property 69
Summary (cont'd.) You can use the Focus method to move the focus to a control during run time Test a procedure immediately after coding it so you will know where to look if the program contains an error After coding an application, you should test it using both valid and invalid data values to verify that the code is working correctly Programs can contain syntax errors, logic errors, or run time errors 70
Summary (cont'd.) To use the Project Designer window to set Option Explicit, Option Strict, and Option Infer for the current project, right-click My Project in the Solution Explorer window, click Open, click the Compile tab, set the options, and then close the Project Designer window To use the Options dialog box to set Option Explicit, Option Strict, and Option Infer for all of the projects you create, click Tools on the Visual Studio menu bar, click Options, expand the Projects and Solutions node, click VB Defaults, set the options, and then click the OK button 71