Chapter 3: Using Variables and Constants

Slides:



Advertisements
Similar presentations
Tutorial 31 Variable Memory location whose value can change as the program is running. Used to hold temporary information Used to control the type of data.
Advertisements

1.
Chapter 3: Using Variables and Constants Programming with Microsoft Visual Basic 2005, Third Edition.
Objectives Understand the software development lifecycle Perform calculations Use decision structures Perform data validation Use logical operators Use.
Chapter 11: Classes and Objects
Programming with Microsoft Visual Basic th Edition
Chapter 7: Sub and Function Procedures
1.
String Variables Visual Basic for Applications 4.
Input Validation Check the values entered into a text box before beginning any calculations Validation is a form of ‘self-protection’, rejecting bad data.
An Introduction to Programming with C++ Fifth Edition Chapter 4 Chapter 4: Variables, Constants, and Arithmetic Operators.
An Introduction to Programming with C++ Fifth Edition Chapter 4 Chapter 4: Variables, Constants, and Arithmetic Operators.
Data Types and Operations Programming Fundamentals (Writing Code)Programming Fundamentals (Writing Code)
Chapter 3: Introducing the Microsoft.NET Framework and Visual Basic.NET Visual Basic.NET Programming: From Problem Analysis to Program Design.
Chapter 7: Sub and Function Procedures
Chapter Three Using Variables and Constants Programming with Microsoft Visual Basic th Edition.
1 Chapter Two Using Data. 2 Objectives Learn about variable types and how to declare variables Learn how to display variable values Learn about the integral.
Chapter 8: String Manipulation
Variables, Constants, Methods, and Calculations Chapter 3 - Review.
Programming with Microsoft Visual Basic th Edition CHAPTER SEVEN SUB AND FUNCTION PROCEDURES.
Programming with Microsoft Visual Basic 2012 Chapter 7: Sub and Function Procedures.
Programming with Microsoft Visual Basic 2008 Fourth Edition Chapter Seven Sub and Function Procedures.
Chapter 3: Using Variables and Constants
Programming with Microsoft Visual Basic th Edition CHAPTER THREE USING VARIABLES AND CONSTANTS.
Chapter Four The Selection Structure
Microsoft Visual Basic 2008: Reloaded Fourth Edition
Chapter 4: The Selection Structure
Object Variables Visual Basic for Applications 3.
Tutorial 11 Using and Writing Visual Basic for Applications Code
Microsoft Visual Basic 2010: Reloaded Fourth Edition Chapter Six Repeating Program Instructions.
Programming with Microsoft Visual Basic 2008 Fourth Edition
Chapter 4: The Selection Structure
Chapter 2: Using Data.
Computer Programming TCP1224 Chapter 4 Variables, Constants, and Arithmetic Operators.
Microsoft Visual Basic 2005 CHAPTER 4 Variables and Arithmetic Operations.
Chapter 4 Variables and constants. 4.1 Variables -Use of variables is good programming style -easier to modify -easier for a programmer to understand.
Date Variables Visual Basic for Applications 5. Objectives n In this tutorial, you will learn how to: n Reserve a Date variable n Use an assignment statement.
Microsoft Visual Basic 2005: Reloaded Second Edition Chapter 3 Variables, Constants, Methods, and Calculations.
Microsoft Visual Basic 2010: Reloaded Fourth Edition Chapter Three Memory Locations and Calculations.
Chapter 4 Variables and constants. 4.1 Variables -Use of variables is good programming style -easier to modify -easier for a programmer to understand.
Chapter Four The Selection Structure Programming with Microsoft Visual Basic th Edition.
Programming with Microsoft Visual Basic 2008 Fourth Edition Chapter Three Using Variables and Constants.
 2008 Pearson Education, Inc. All rights reserved JavaScript: Introduction to Scripting.
Programming with Microsoft Visual Basic th Edition
Tutorial 3: Using Variables and Constants1 Tutorial 3 Using Variables and Constants.
Chapter 4 Getting Started with VBA. Subroutines Subroutine is the logical section of code that performs a particular task. Subroutine is also called a.
Variables in VB.NET. Variables  A storage location in memory (RAM)  Holds data/information while the program is running  These storage locations can.
1 Writing Software Kashef Mughal. 2 Algorithms  The term algorithm (pronounced AL-go-rith-um) is a procedure or formula for solving a problem.  An Algorithm.
Clearly Visual Basic: Programming with Visual Basic 2008 Chapter 13 How Long Can This Go On?
An Introduction to Programming with C++ Sixth Edition Chapter 13 Strings.
Tutorial 3: Using Variables and Constants1 Tutorial 3 Using Variables and Constants.
Variables and Expressions Programming Right from the Start with Visual Basic.NET 1/e 7.
Microsoft Visual Basic 2012 CHAPTER FOUR Variables and Arithmetic Operations.
Chapter 4: Variables, Constants, and Arithmetic Operators Introduction to Programming with C++ Fourth Edition.
Microsoft Visual Basic 2012: Reloaded Fifth Edition Chapter One An Introduction to Visual Basic 2012.
Chapter 4 Chapter 4: Variables, Constants, and Arithmetic Operators.
Slide 1 Chapter 3 Variables  A variable is a name for a value stored in memory.  Variables are used in programs so that values can be represented with.
Programming with Microsoft Visual Basic 2012 Chapter 3: Using Variables and Constants.
© 2006 Lawrenceville Press Slide 1 Chapter 4 Variables  A variable is a name for a value stored in memory.  Variables are created using a declaration.
Slide 1 Chapter 3 Variables  A variable is a name for a value stored in memory.  Variables are created using a declaration statement. For example: Dim.
Chapter 2 Variables and Constants. Objectives Explain the different integer variable types used in C++. Declare, name, and initialize variables. Use character.
A variable is a name for a value stored in memory.
Chapter 3: Using Variables and Constants
Chapter 4: The Selection Structure
Programming with Microsoft Visual Basic 2008 Fourth Edition
Variables and Arithmetic Operations
Visual Basic Programming Chapter Four Notes Working with Variables, Constants, Data Types, and Expressions GROUPBOX CONTROL The _____________________________________.
CIS16 Application Development Programming with Visual Basic
An Introduction to Programming with C++ Fifth Edition
Variables and Constants
Presentation transcript:

Chapter 3: Using Variables and Constants Programming with Microsoft Visual Basic .NET, Second Edition

Creating Variables and Named Constants Lesson A Objectives Create a procedure-level and module-level variable Select an appropriate data type for a variable Select an appropriate name for a variable Programming with Microsoft Visual Basic .NET, Second Edition

Creating Variables and Named Constants Lesson A Objectives (continued) Assign data to an existing variable Explain the scope and lifetime of a variable Create a named constant Programming with Microsoft Visual Basic .NET, Second Edition

Previewing the Completed Application To preview the completed Skate-Away Sales application: Use the Run command on the Start menu to run the Skate (Skate.exe) file contained in the VBNET\Chap03 folder An order form similar to the one that you created in Chapter 2 appears on the screen Programming with Microsoft Visual Basic .NET, Second Edition

Using Variables to Store Information Besides storing data in the properties of controls, a programmer also can store data, temporarily, in memory locations inside the computer The memory locations are called variables, because the contents of the locations can change as the program is running Programming with Microsoft Visual Basic .NET, Second Edition

Using Variables to Store Information (continued) One use for a variable is to hold information that is not stored in a control on the user interface You can also store the data contained in a control’s property in a variable Programming with Microsoft Visual Basic .NET, Second Edition

Selecting a Data Type for a Variable Memory Required Byte 1 byte Short 2 bytes Char Integer 4 bytes Boolean Long 8 bytes Decimal 16 bytes Single Double String Varies Date Object Programming with Microsoft Visual Basic .NET, Second Edition

Selecting a Data Type for a Variable (continued) Short, Integer, Long Store whole numbers Single, Double Store floating-point numbers Decimal Stores numbers with a decimal point Boolean Stores True and False Char Stores one Unicode character Byte Stores 8-bits of data Date Stores date and time information String Stores a sequence of characters Programming with Microsoft Visual Basic .NET, Second Edition

Selecting a Name for a Variable The naming convention used in this book: The name indicates only the variable’s purpose and is entered using lowercase letters Use camel casing: if a variable’s name contains two or more words, you capitalize the first letter in the second and subsequent words The name assigned to a variable must follow the rules listed in Figure 3-4 Programming with Microsoft Visual Basic .NET, Second Edition

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 .NET, Second Edition

Declaring a Variable You use a declaration statement to declare, or create, a variable Syntax: {Dim | Private | Static} variablename [As datatype][= initialvalue] Examples: Dim hoursWorked As Integer Dim dataOk As Boolean = True Dim name As String, age As Integer Programming with Microsoft Visual Basic .NET, Second Edition

Assigning Data to an Existing Variable You use an assignment statement to assign a value to a variable while an application is running Syntax: variablename = value Examples: quantityOrdered = 500 firstName = “Mary” state = Me.uiStateTextBox.Text discountRate = .03 Programming with Microsoft Visual Basic .NET, Second Edition

Assigning Data to an Existing Variable (continued) A literal constant is an item whose value does not change while the application is running String literal constants are enclosed in quotation marks, but numeric literal constants and variable names are not A literal type character forces a literal constant to assume a data type other than the one its form indicates Programming with Microsoft Visual Basic .NET, Second Edition

Assigning Data to an Existing Variable (continued) Figure 3-7: Literal type characters Programming with Microsoft Visual Basic .NET, Second Edition

Assigning Data to an Existing Variable (continued) A variable can store only one item of data at any one time When you use an assignment statement to assign another item to the variable, the new data replaces the existing data After data is stored in a variable, you can use the data in calculations Programming with Microsoft Visual Basic .NET, Second Edition

The Parse Method Every numeric data type in Visual Basic .NET has a Parse method that can be used to convert a string to that numeric data type Syntax: numericDataType.Parse(string) Example: Dim sales As Decimal sales = Decimal.Parse(Me.uiSalesTextBox.Text) Programming with Microsoft Visual Basic .NET, Second Edition

The Convert Class The Convert class contains methods to convert a numeric value to a specified data type Syntax: Convert.method(value) Example: Dim purchase As Double = 500 Dim tax As Decimal tax = Convert.ToDecimal(purchase) * .03D Programming with Microsoft Visual Basic .NET, Second Edition

The Convert Class (continued) Figure 3-9: Most commonly used methods contained in the Convert class Programming with Microsoft Visual Basic .NET, Second Edition

The Scope and Lifetime of a Variable A variable’s scope indicates which procedures in an application can use the variable The scope is determined by where the Dim, Public or Private statement is entered When you declare a variable in a procedure, the variable is called a procedure-level variable and is said to have procedure scope Programming with Microsoft Visual Basic .NET, Second Edition

The Scope and Lifetime of a Variable (continued) When you declare a variable in the form’s Declarations section, it is called a module-level variable and is said to have module scope Block-level variables are declared within specific blocks of code, such as within If...Then...Else statements or For...Next statements Programming with Microsoft Visual Basic .NET, Second Edition

The Scope and Lifetime of a Variable (continued) Creating a procedure-level variable Created with the Dim keyword The Dim statement is entered in an object’s event procedure Only the procedure in which it is declared can use the variable Removed from memory when the procedure ends Programming with Microsoft Visual Basic .NET, Second Edition

The Scope and Lifetime of a Variable (continued) Creating a module-level variable Created with the Private keyword Entered in a form’s Declarations section Can be used by any of the procedures in the form Removed from memory when the application ends or the form is destroyed Programming with Microsoft Visual Basic .NET, Second Edition

Named Constants A memory location whose contents cannot be changed while the program is running You create a named constant using the Const statement Syntax: Const constantname [As datatype] = expression Example: Const PI As Double = 3.141593 Programming with Microsoft Visual Basic .NET, Second Edition

Option Explicit and Option Strict Visual Basic .NET provides a way to prevent you from using undeclared variables in your code Enter the statement Option Explicit On in the General Declarations section of the Code Editor window Programming with Microsoft Visual Basic .NET, Second Edition

Option Explicit and Option Strict (continued) To eliminate the problems that occur as a result of implicit type conversions Enter the Option Strict On statement in the General Declarations section of the Code Editor window Programming with Microsoft Visual Basic .NET, Second Edition

Option Explicit and Option Strict (continued) Type conversion rules used when the Option Strict On statement is used: Strings will not be implicitly converted to numbers, and numbers will not be implicitly converted to strings Lower-ranking data types will be implicitly promoted to higher-ranking types Higher-ranking data types will not be implicitly demoted to lower-ranking data types; rather, a syntax error will occur Programming with Microsoft Visual Basic .NET, Second 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 Designate the default button for a form Programming with Microsoft Visual Basic .NET, Second Edition

Storing Information Using Variables You need to revise the Skate-Away Sales application’s TOE chart and the pseudocode for the Calculate Order button The uiCalcButton control’s Click event procedure now has two more tasks to perform: It must calculate the sales tax It must display the message, sales tax, and salesperson’s name in the uiMessageLabel control Programming with Microsoft Visual Basic .NET, Second Edition

Storing Information Using Variables (continued) Two additional objects (OrderForm and uiMessageLabel) are included in the revised TOE chart The OrderForm’s Load event procedure is responsible for getting the salesperson’s name when the application is started The uiMessageLabel control will display the message, sales tax, and salesperson’s name Programming with Microsoft Visual Basic .NET, Second Edition

Storing Information Using Variables (continued) As the revised TOE chart indicates, you need to: Change the code in the uiCalcButton’s Click event procedure Code the form’s Load event procedure Programming with Microsoft Visual Basic .NET, Second Edition

Modifying the Calculate Order Button’s Code You will first remove the existing code from the Calculate Order button’s Click event procedure You then will recode the procedure using variables in the equations Figure 3-18 shows the revised pseudocode for the Calculate Order button’s Click event procedure (changes made to the original pseudocode are shaded in the figure) Programming with Microsoft Visual Basic .NET, Second Edition

Modifying the Calculate Order Button’s Code (continued) Figure 3-18: Revised pseudocode for the Calculate Order button’s Click event procedure Programming with Microsoft Visual Basic .NET, Second Edition

Concatenating Strings Connecting strings together is called concatenating Use the concatenation operator, which is the ampersand (&), to concatenate strings in Visual Basic .NET When concatenating strings, be sure to include a space before and after the concatenation operator Programming with Microsoft Visual Basic .NET, Second Edition

Concatenating Strings (continued) Example Result firstName & lastName SueChen firstName & “ “ & lastName Sue Chen lastName & “, “ & firstName Chen, Sue “She is “ & Convert.ToString(age) & “!” She is 21! “She is “ & age & “!” Programming with Microsoft Visual Basic .NET, Second Edition

The InputBox Function The InputBox function displays one of Visual Basic .NET’s predefined dialog boxes Syntax: InputBox(prompt[, title][, defaultResponse]) Use sentence capitalization for the prompt, and book title capitalization for the title Has limitations: can’t control appearance and allows user to enter only one piece of data Programming with Microsoft Visual Basic .NET, Second Edition

The InputBox Function (continued) Figure 3-29: Example of a dialog box created by the InputBox function Programming with Microsoft Visual Basic .NET, Second Edition

The NewLine Character The NewLine character, which is Chr(13) & Chr(10), instructs the computer to issue a carriage return followed by a line feed The ControlChars.NewLine constant advances the insertion point to the next line on the screen The ControlChars.NewLine constant is an intrinsic constant, which is a named constant that is built into Visual Basic .NET Programming with Microsoft Visual Basic .NET, Second Edition

Designating a Default Button Can be selected by pressing the Enter key even when the button does not have the focus Set the form’s AcceptButton property to the desired button If used, it is typically the first button If a button’s action is destructive and irreversible, then it should not be the default button Programming with Microsoft Visual Basic .NET, Second 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 Programming with Microsoft Visual Basic .NET, Second Edition

Modifying the Code in the Load and uiCalcButton Click Procedures Mr. Cousard would like to have the order form ask for the salesperson’s name each time an order is calculated Before making modifications, you should review the application’s documentation and revise the necessary documents Figure 3-44 shows the revised pseudocode for the Calculate Order button’s Click event procedure Programming with Microsoft Visual Basic .NET, Second Edition

Modifying the Code in the Load and uiCalcButton Click Procedures (continued) Figure 3-44: Revised pseudocode for the Calculate Order button Programming with Microsoft Visual Basic .NET, Second Edition

Static Variables A static variable is a local variable that retains its value when the procedure in which it is declared ends Syntax: Static variablename [As datatype] [= initialvalue] Removed from memory when application ends or form is removed from memory Programming with Microsoft Visual Basic .NET, Second Edition

Coding the TextChanged Event Procedure A control’s TextChanged event occurs when the contents of a control’s Text property change This can happen as a result of either the user entering data into the control, or the application’s code assigning data to the control’s Text property Programming with Microsoft Visual Basic .NET, Second Edition

Associating a Procedure with Different Objects or Events The keyword Handles appears in a procedure header and indicates the object and event associated with the procedure You can associate a procedure with more than one object and event To do so: list each object and event, separated by commas, in the Handles section of the procedure header Programming with Microsoft Visual Basic .NET, Second Edition

Summary The syntax of a variable declaration statement is: {Dim | Private | Static} variablename [As datatype][= initialvalue] To create a procedure-level variable, enter the variable declaration statement in a procedure To create a module-level variable, enter the variable declaration statement in a form’s Declarations section Programming with Microsoft Visual Basic .NET, Second Edition

Summary (continued) To concatenate strings, use the concatenation operator —the ampersand (&) To display a dialog box containing a prompt, an input area, an OK button, and a Cancel button, use the InputBox function, whose syntax is InputBox(prompt[, title][, defaultResponse]) To make a button the default button, set the form’s AcceptButton property to the name of the button Programming with Microsoft Visual Basic .NET, Second Edition

Summary (continued) To create a static variable, use a declaration statement that follows the syntax: Static variablename [As datatype] [= initialvalue] To process code when the contents of a control have changed, enter the code in the control’s TextChanged event To create a procedure for more than one object or event, list each object and event after the Handles keyword in the procedure Programming with Microsoft Visual Basic .NET, Second Edition