Microsoft Visual Basic: Reloaded Chapter Three Memory Locations and Calculations
2009 Pearson Education, Inc. All rights reserved. 2 ■Class Definitions ■Events and Event Handlers ■Adding Code to an Event Handler ■Val Function and TextChanged Event ■Declaring Variables ■TryParse and Convert Class Methods ■Arithmetic (+,-,*,/,\,^,Mod) ■Variable Scope and Lifetime ■Option Explicit, Infer and Strict ■Debugging Errors and Debugger Breakpoints Overview
2009 Pearson Education, Inc. All rights reserved. Class Definitions ■Most Visual Basic programs consist of pieces called classes, which simplify application organization. ■Classes contain groups of code statements that perform tasks and return information when the tasks are completed. These lines collectively are called a class definition. ■Most Visual Basic applications consist of a combination of code written by programmers and preexisting classes written and provided by Microsoft in the.NET Framework Class Library. 3
2009 Pearson Education, Inc. All rights reserved. Class Definition and Code Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click MessageBox.Show("Hello World!") End Sub End Class 4
2009 Pearson Education, Inc. All rights reserved. Class Definitions ■The Class keyword introduces a class definition in Visual Basic and is followed by the class name. ■The name of the class is an identifier An identifier is a series of characters consisting of letters, digits and underscores. Identifiers cannot begin with a digit and cannot contain spaces. ■The class definition ends with the keywords End Class. 5
2009 Pearson Education, Inc. All rights reserved. Events and Event Handlers ■GUI events, represent user actions, such as clicking a Button or altering a value in a TextBox. ■Event handlers are pieces of code that execute when such events occur. ■When you double click a control, the IDE inserts the default event handler for that control. Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click End Sub 6
2009 Pearson Education, Inc. All rights reserved. 7 ■Button: Click ■Text Box: TextChanged ■Radio Button: CheckedChanged ■Check Box: CheckedChanged ■Combo Box: SelectedIndexChanged ■Double click on the control in design view to automatically open the code window with the default event for that control. Default Control Events
2009 Pearson Education, Inc. All rights reserved. 8 ■Enter ■TextChanged ■KeyDown ■MouseEnter ■MouseLeave ■MouseHover ■And many more (68 in all) which can be explored in the Object Browser, Properties Window or Code Window Other Command Button Events
2009 Pearson Education, Inc. All rights reserved. 9 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click End Sub ■When event eventName occurs on the control controlName, event handler controlName_eventName executes. ■When event Click occurs on the control Button1, event handler Button1_Click executes. ■The Handles clause indicates that the event handler is called when the Button ’s Click event occurs. Default Event Handler for Button
2009 Pearson Education, Inc. All rights reserved. 10 ■Message statements give information to the user ■Declaration statements set variable names and variable types ■Assignment statements assign a value to a variable ■Comparison statements compare one value to another. They ask a true/false question. ■Decision statements execute different lines of code based on a comparison ■Looping statements execute blocks of code again and again Common Programming Statements
2009 Pearson Education, Inc. All rights reserved. Adding Code to an Event Handler 11 Figure 5.11 | Running the application with the event handler.
2009 Pearson Education, Inc. All rights reserved. 12 Public Class InventoryForm Private Sub calculateButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles calculateButton.Click totalResultLabel.Text = cartonsTextBox.Text _ * itemsTextBox.Text End Sub End Class Adding Code to an Event Handler
2009 Pearson Education, Inc. All rights reserved. Adding Code to an Event Handler ■In Visual Basic, properties are accessed in code by placing a period between the control name. This period is called the member-access operator (.), or the dot operator. ■The underscore character is the line-continuation character. At least one space character must precede each line- continuation character. Only whitespace characters (space, tab or newline) can follow the underscore 13
2009 Pearson Education, Inc. All rights reserved. Adding Code to an Event Handler ■The “ =” symbol is known as the assignment operator. ■The expressions on either side of the assignment operator are referred to as its operands. This assignment operator assigns the value on the right of the operator (the right operand) to the variable on the left of the operator (the left operand). ■The assignment operator is known as a binary operator. ■The asterisk (*) is known as the multiplication operator. Its left and right operands are multiplied together. 14
2009 Pearson Education, Inc. All rights reserved. 15 Public Class InventoryForm Private Sub calculateButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles calculateButton.Click totalResultLabel.Text = Val(cartonsTextBox.Text) * _ Val(itemsTextBox.Text) End Sub End Class Enhancing the Code with the Val Function
2009 Pearson Education, Inc. All rights reserved. Val Function ■The Val function prevents nonnumeric inputs from terminating the application. A function is a piece of code that performs a task when called and returns a value. The values returned by Val become the values used in the multiplication expression. ■Call functions by typing their name followed by parentheses. Val (“2 3kdd.3”) 16
2009 Pearson Education, Inc. All rights reserved. Val Function ■Once a nonnumeric character is read, Val returns the number it has read up to that point. Val ignores whitespace characters. Val (“2 34”) returns 234 Val does not recognize symbols such as commas and dollar signs. Val (“1,005”) returns 1 If function Val receives an argument that cannot be converted to a number, it returns 0. Val (“abc123”) returns 0 ■ Val recognizes the decimal point as a numeric character, as well as the plus and minus signs when they appear at the beginning of the string. 17
2009 Pearson Education, Inc. All rights reserved. Val Function 18 Figure 5.13 | Val function call examples.
2009 Pearson Education, Inc. All rights reserved. Enhancing the Inventory Application 19 ■The result displayed in the Total: Label will be removed (Fig. 6.3) when the user enters a new quantity in either TextBox. Figure 6.3 | Enhanced Inventory application clears output Label after new input. Cleared output Label
2009 Pearson Education, Inc. All rights reserved. TextChanged Event ■Double click the Cartons per shipment: TextBox to generate an event handler for the TextChanged event (Fig. 6.9). ■The notation "" in line 28 is called an empty string, which is a value that does not contain any characters. 20 Figure 6.9 | TextChanged event handler for Cartons per shipment: TextBox. TextChanged event handler
2009 Pearson Education, Inc. All rights reserved. Internal Memory ■Internal memory: a component inside a computer comprised of memory locations ■Each memory location has a unique numeric address and can hold only one item at a time ■A programmer can reserve memory locations for a program by assigning each location a name, a data type, and an initial value ■Data type: indicates the type of data the memory location will store ■Two types of memory locations that a programmer can declare: variables and constants
2009 Pearson Education, Inc. All rights reserved. Variables ■Variables: computer memory locations used to temporarily store data while an application is running Contents can change during run time ■Use a meaningful variable name that reflects the purpose of the variable ■Use camel casing for variable identifiers ■Variable names should conform to naming rules ■All variables must be declared by using program code. Declarations that you’ll make within event handlers begin with the keyword Dim.
2009 Pearson Education, Inc. All rights reserved. Variables ■Variable names—such as cartons, items and result —correspond to actual locations in the computer’s memory. ■Every variable has a name, type, size and value. cartons = Val(cartonsTextBox.Text) ■Whenever a value is placed in a memory location, this value replaces the value previously stored in that location. The previous value is overwritten (lost). ■Whenever a value is read from a memory location, the process is nondestructive. 23
2009 Pearson Education, Inc. All rights reserved.
Variable Data Types ■Each variable must be assigned a data type, which determines the memory location’s data type ■Each data type is a class Integer, Long, or Short data types can store integers (whole numbers) Decimal, Double, and Single data types: store real numbers (numbers with a decimal place) Char data type: stores one Unicode character String data type: stores multiple Unicode characters
2009 Pearson Education, Inc. All rights reserved. Figure 3-3: Basic data types in Visual Basic
2009 Pearson Education, Inc. All rights reserved. Declaring a Variable in Code ■Declaration statement: used to declare, or create, a variable Declaration statement includes: Scope keyword: Dim, Private, or Static Name of the variable and data type Initial value (optional) ■Initialization Numeric data types: automatically initialized to 0 String data type: automatically initialized to Nothing Boolean data type: initialized to False
2009 Pearson Education, Inc. All rights reserved. Declaring a Variable in Code (cont’d.)
2009 Pearson Education, Inc. All rights reserved. Declaring a Variable in Code (cont’d.)
2009 Pearson Education, Inc. All rights reserved. Use keyword Dim to declare variables inside an event handler Assigning a property’s value to a variable
2009 Pearson Education, Inc. All rights reserved. 31 Assigning a variable’s value to a property Setting a Label’s Text property to an empty string
2009 Pearson Education, Inc. All rights reserved. Implicit Conversion ■The Val function returns a numerical value as data type Double when converting a value retrieved from a TextBox’ s Text property. ■Lines 13–14 implicitly convert the Double s to Integer values. This process is called implicit conversion because the conversion is performed by Visual Basic without any additional code. Implicit conversions from Double to Integer are generally considered poor programming practice due to the potential loss of information. 32
2009 Pearson Education, Inc. All rights reserved. Using the TryParse Method ■ TryParse method: Part of every numeric data type’s class Used to convert a string to that numeric data type ■Argument: a value that is provided to a method ■Basic syntax of TryParse method has two arguments: String: string value to be converted Variable: location to store the result ■If TryParse conversion is successful, the method stores the value in the variable ■If unsuccessful, a 0 is stored in the numeric variable
2009 Pearson Education, Inc. All rights reserved. Figure 3-6: How to use the basic syntax of the TryParse method
2009 Pearson Education, Inc. All rights reserved. Using the TryParse Method (cont'd.)
2009 Pearson Education, Inc. All rights reserved. Using the Convert Class Methods ■ Convert class: Contains methods for converting numeric values to specific data types ■Commonly used methods of the Convert class include: ToDouble ToDecimal ToInt32 ToString
2009 Pearson Education, Inc. All rights reserved. Using the Convert Class Methods (cont’d.)
2009 Pearson Education, Inc. All rights reserved. Arithmetic 38 Figure 6.15 | Arithmetic operators.
2009 Pearson Education, Inc. All rights reserved. Arithmetic ■Arithmetic expressions in Visual Basic must be written in straight-line form so that you can type them into a computer. For example, the division of 7.1 by 4.3 must be written as 7.1 / 4.3. Also, raising 3 to the second power cannot be written as 3 2 but is written in straight-line form as 3 ^ 2. ■Parentheses are used in Visual Basic expressions to group operations in the same manner as in algebraic expressions. To multiply a times the quantity b + c, you write a * ( b + c ) 39
2009 Pearson Education, Inc. All rights reserved. Rules of Operator Precedence ■Expressions in parentheses are evaluated first. With nested parentheses, the operators contained in the innermost pair of parentheses are applied first. ■Exponentiation ■Unary positive and negative, + and - ■Multiplication and floating-point division ■ Integer division ■Modulus operations ■Addition and subtraction Operators of the same type are applied from left to right. 40
2009 Pearson Education, Inc. All rights reserved. Rules of Operator Precedence ■Let’s consider several expressions in light of the rules of operator precedence. The following calculates the average of three numbers: Algebra:m = ( a + b + c ) 3 Visual Basic: m = ( a + b + c ) / 3 The parentheses are required because floating-point division has higher precedence than addition. The following is the equation of a straight line: Algebra:y = mx + b Visual Basic: y = m * x + b No parentheses are required due to operator precedence. 41
2009 Pearson Education, Inc. All rights reserved. Rules of Operator Precedence ■Consider how the expression y = ax 2 + bx + c is evaluated: ■It is acceptable to place redundant parentheses in an expression to make the expression easier to read. y = ( a * ( x ^ 2 ) ) + ( b * x ) + c 42
2009 Pearson Education, Inc. All rights reserved. Integer and Floating-Point Division ■Visual Basic has separate operators for integer division (the backslash, \ ) and floating-point division (the forward slash, / ). Floating-point division divides two numbers and returns a floating-point number. The operator for integer division treats its operands as integers and returns an integer result. ■Attempting to divide by zero is a runtime error (that is, an error that has its effect while the application executes). Dividing by zero terminates an application. 43
2009 Pearson Education, Inc. All rights reserved. Integer Division Rounding ■When floating-point numbers (numbers with decimal points) are used with the integer-division operator, the numerators and denominators are first rounded as follows: numbers ending in.5 are rounded to the nearest even integer — for example, 6.5 rounds down to 6 and 7.5 rounds up to 8 all other floating-point numbers are rounded to the nearest integer — for example, 7.1 rounds down to 7 and 7.7 rounds up to 8. ■Any fractional part of the integer division result is truncated. 44
2009 Pearson Education, Inc. All rights reserved. Modulus Operator ■The modulus operator, Mod, yields the remainder after division. ■Thus, 7 Mod 4 yields 3, and 17 Mod 5 yields 2. ■This operator is used most commonly with Integer operands. ■The modulus operator can be used to discover whether one number is a multiple of another. 45
2009 Pearson Education, Inc. All rights reserved. Integer Division and Modulus Examples
2009 Pearson Education, Inc. All rights reserved.
Variables and Arithmetic Operators
2009 Pearson Education, Inc. All rights reserved. Arithmetic Assignment Operators
2009 Pearson Education, Inc. All rights reserved.
The Scope and Lifetime of a Variable ■Scope: indicates where the variable can be used ■Lifetime: indicates how long the variable remains in memory ■Variables can have class scope, procedure scope, or block scope ■A variable’s scope and lifetime are determined by where you declare the variable Variables declared in the form’s Declarations section have class scope Variables declared within a procedure have either procedure scope or block scope
2009 Pearson Education, Inc. All rights reserved. Variables with Procedure Scope ■Procedure-level variable: declared within a procedure Use the Dim keyword in the declaration ■Procedure scope: only the procedure can use the variable With procedure-level scope, two procedures can each use the same variable names
2009 Pearson Education, Inc. All rights reserved. Figure 3-14: The MainForm in the Sales Tax application Figure 3-15: Examples of using procedure-level variables
2009 Pearson Education, Inc. All rights reserved. Variables with Class Scope ■Class scope: variable can be used by all procedures in the form ■Class-level variable: Declared in the form’s Declarations section Use Private keyword in declaration ■Class-level variables retain their values until the application ends
2009 Pearson Education, Inc. All rights reserved. Figure 3-17: Example of using a class-level variable
2009 Pearson Education, Inc. All rights reserved. Static Variables ■Static variable: Procedure-level variable that remains in memory and retains its value even after the procedure ends Retains its value until the application ends (like a class-level variable), but can only be used by the procedure in which it is declared ■A static variable has: Same lifetime as a class-level variable Narrower scope than a class-level variable ■Declared using the Static keyword
2009 Pearson Education, Inc. All rights reserved. Static Variables
2009 Pearson Education, Inc. All rights reserved. Named Constants ■Named constant: memory location whose value cannot be changed while the application is running Declared using the Const keyword Good programming practice to specify the data type as well Many programmers use Pascal case for named constants ■Literal type character: forces a literal constant to assume a specific data type ■Named constants help to document the program code
2009 Pearson Education, Inc. All rights reserved.
Figure 3-20: Area Calculator application’s interface Figure 3-21: Example of using a named constant
2009 Pearson Education, Inc. All rights reserved. Option Explicit, Option Infer, and Option Strict
2009 Pearson Education, Inc. All rights reserved. Option Explicit, Option Infer, and Option Strict (cont'd.) ■Option Explicit On statement enforces that all variables must be declared before being used ■Undeclared variable: a variable that does not appear in a declaration statement (such as Dim ) Is assigned a data type of Object ■Misspelling a variable name can result in an undeclared variable unless Option Explicit is on
2009 Pearson Education, Inc. All rights reserved. Option Explicit, Option Infer, and Option Strict (cont'd.) ■Option Infer Off statement: ensures that every variable is declared with a data type
2009 Pearson Education, Inc. All rights reserved. Option Explicit, Option Infer, and Option Strict (cont'd.) ■Option Strict On statement: ensures that values cannot be converted from one data type to a narrower data type, resulting in lost precision ■Implicit type conversion: occurs when you attempt to assign data of one type to a variable of another type without explicitly attempting to convert it If converted to a data type that can store larger numbers, the value is said to be promoted If converted to a data type that can store only smaller numbers, the value is said to be demoted. This can cause truncation and loss of precision (not good!)
2009 Pearson Education, Inc. All rights reserved.
Debugging Errors ■Debugging is the process of fixing errors in an application. ■The Visual Basic IDE contains a debugger that allows you to analyze the behavior of your application. ■There are two types of errors—compilation errors and logic errors. 66
2009 Pearson Education, Inc. All rights reserved. Debugging Errors ■Compilation errors occur when code statements violate the grammatical rules of the programming language or when code statements are simply incorrect in the current context. Syntax errors are compilation errors that are violations of the grammatical rules of the programming language. ■Logic errors do not prevent the application from compiling successfully, but do cause the application to produce erroneous results. 67
2009 Pearson Education, Inc. All rights reserved. Debugger Breakpoints ■A breakpoint is a marker that can be set at any executable line of code. ■When application execution reaches a breakpoint, execution pauses, allowing you to peek inside your application and ensure that there are no logic errors. 68
2009 Pearson Education, Inc. All rights reserved. Debugger Breakpoints ■To insert a breakpoint in the IDE, either click inside the margin indicator bar next to a line of code, or right click that line of code and select Breakpoint > Insert Breakpoint Fig. 6.16). ■The application is said to be in break mode when the debugger pauses the application’s execution. 69 Figure 6.16 | Setting two breakpoints. Margin indicator bar Breakpoints
2009 Pearson Education, Inc. All rights reserved. Debugger Breakpoints 70 ■After setting breakpoints in the code editor, select Debug > Start Debugging to begin the debugging process (Fig. 6.17, Fig. 6.18). Figure 6.17 | Inventory application running. Figure 6.18 | Title bar of the IDE displaying (Debugging). Title bar displays ( Debugging )
2009 Pearson Education, Inc. All rights reserved. Debugger Breakpoints 71 ■Application execution suspends at the first breakpoint, and the IDE becomes the active window (Fig. 6.19). The yellow arrow to the left of line 17 indicates that this line contains the next statement to execute. Figure 6.19 | Application execution suspended at the first breakpoint. Yellow arrow Breakpoints Next executable statement
2009 Pearson Education, Inc. All rights reserved. Debugger Breakpoints 72 ■To resume execution, select Debug > Continue (or press F5). ■Note that when you place your mouse pointer over the variable name result, the value that the variable stores is displayed in a Quick Info box (Fig. 6.20). Figure 6.20 | Displaying a variable value by placing the mouse pointer over a variable name. Quick Info box displays variable result’s value
2009 Pearson Education, Inc. All rights reserved. Debugger Breakpoints 73 ■Use the Debug > Continue command to complete the application execution. When there are no more breakpoints at which to suspend execution, the application executes to completion (Fig. 6.21). Figure 6.21 | Application output.
2009 Pearson Education, Inc. All rights reserved. Formatting Numeric Output ■Formatting: specifying the number of decimal places and any special characters to display ■ ToString method of a variable can be used to format a number ■FormatString argument: specifies the type of formatting to use ■Precision specifier: controls the number of significant digits or zeros to the right of the decimal point
2009 Pearson Education, Inc. All rights reserved.
Figure 3-39: The calcButton’s modified Click event procedure