Chapter 3: Using Variables and Constants Programming with Microsoft Visual Basic 2005, Third Edition.

Slides:



Advertisements
Similar presentations
Programming with Microsoft Visual Basic th Edition
Advertisements

Chapter 3: Using Variables and Constants
1.
Lecture Set 4 Data Types and Variables Part B – Variables, Constants, Expressions Conversion Rules Options Strict, Option Explicit Scope of Definition.
Objectives Understand the software development lifecycle Perform calculations Use decision structures Perform data validation Use logical operators Use.
Chapter 11: Classes and Objects
Microsoft Visual Basic 2010: Reloaded Fourth Edition Chapter Eight Sub and Function Procedures.
1.
Programming with Microsoft Visual Basic 2005, Third Edition
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.
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
Chapter 4: The Selection Structure
Microsoft Visual Basic 2010: Reloaded Fourth Edition Chapter Six Repeating Program Instructions.
CHAPTER THREE Representing Data: Constants and Variables.
Programming with Microsoft Visual Basic 2008 Fourth Edition
Chapter 4: The Selection Structure Programming with Microsoft Visual Basic 2005, Third Edition.
Chapter 4: The Selection Structure
Chapter 3 Processing and Interactive Input. 2 Assignment  The general syntax for an assignment statement is variable = operand; The operand to the right.
Input, Output, and Processing
Chapter Ten Structures and Sequential Access Files Programming with Microsoft Visual Basic th Edition.
Computer Programming TCP1224 Chapter 4 Variables, Constants, and Arithmetic Operators.
Representing Data: Constants and Variables CHAPTER THREE Matakuliah: T0063 – Pemrograman Visual Tahun: 2009.
Microsoft Visual Basic 2005 CHAPTER 4 Variables and Arithmetic Operations.
Chapter 6: The Repetition Structure
Chapter 5: More on the Selection Structure Programming with Microsoft Visual Basic 2005, Third Edition.
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.
Programming with Microsoft Visual Basic 2008 Fourth Edition Chapter Three Using Variables and Constants.
Programming with Microsoft Visual Basic th Edition
Tutorial 3: Using Variables and Constants1 Tutorial 3 Using Variables and Constants.
Programming with Microsoft Visual Basic 2008 Fourth Edition Chapter Ten Structures and Sequential Access Files.
Programming with Microsoft Visual Basic 2008 Fourth Edition Chapter Eight String Manipulation.
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.
CHAPTER THREE Representing Data: Constants and Variables.
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 3: Introducing the Microsoft.NET Framework and Visual Basic.NET Visual Basic.NET Programming: From Problem Analysis to Program Design.
Chapter 4: Variables, Constants, and Arithmetic Operators Introduction to Programming with C++ Fourth Edition.
Chapter 4 Chapter 4: Variables, Constants, and Arithmetic Operators.
Chapter 4.  Variables – named memory location that stores a value.  Variables allows the use of meaningful names which makes the code easier to read.
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.
Representing Data: Constants and Variables
Microsoft Visual Basic 2010 CHAPTER FOUR Variables and Arithmetic Operations.
Egyptian Language School Computer Department
A variable is a name for a value stored in memory.
Variables and Arithmetic Operations
Chapter 3: Using Variables and Constants
Chapter 4: The Selection Structure
Lecture Set 4 Data Types and Variables
Variables and Arithmetic Operations
CIS16 Application Development Programming with Visual Basic
An Introduction to Programming with C++ Fifth Edition
Presentation transcript:

Chapter 3: Using Variables and Constants Programming with Microsoft Visual Basic 2005, Third Edition

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 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 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 Programming with Microsoft Visual Basic 2005, Third Edition Previewing the Completed Application (continued) Figure 3-1: Name Entry dialog box

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 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 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 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 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 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 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 Programming with Microsoft Visual Basic 2005, Third Edition Assigning Data to an Existing Variable (continued) Figure 3-7: Literal type characters

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 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 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 = Me.xTotalLabel.Text = _ Convert.ToString(totalAmountDue) –Line continuation character: underscore in line 2

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 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 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 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 =

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 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 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 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 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 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 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 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 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 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 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 Programming with Microsoft Visual Basic 2005, Third Edition Concatenating Strings (continued) Figure 3-30: Examples of string concatenation

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 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 Programming with Microsoft Visual Basic 2005, Third Edition The InputBox Function (continued) Figure 3-36: MainForm’s Load event procedure

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 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 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 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 to $75.31

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 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 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 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 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 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 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 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 Programming with Microsoft Visual Basic 2005, Third Edition Associating a Procedure with Different Objects and Events (continued) Figure 3-56: Completed ClearControls procedure

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