22
Variables and Constants Variable Memory locations that hold data that can be changed during project execution Example: a customer’s name Constant Memory locations that hold data that cannot be changed during project execution Example: the sales tax rate In VB, use a Declaration statement to establish variables and constants

Variables and Constants

Embed Size (px)

DESCRIPTION

Variables and Constants. Variable Memory locations that hold data that can be changed during project execution Example: a customer’s name Constant Memory locations that hold data that cannot be changed during project execution Example: the sales tax rate - PowerPoint PPT Presentation

Citation preview

Page 1: Variables and Constants

Variables and Constants

Variable

•Memory locations that hold data that can be changed during project execution

•Example: a customer’s name

• Constant

•Memory locations that hold data that cannot be changed during project execution

•Example: the sales tax rate

• In VB, use a Declaration statement to establish variables and constants

Page 2: Variables and Constants

3-

All Variables & Constants Have a Data Type

Boolean True or False value 2

Byte 0 to 255, binary data 1

Clear Single Unicode character 2

Date 1/1/0001 through 12/31/9999 8

Decimal Decimal fractions, such as dollars/cents 16

Single Single precision floating-point numbers with six digits of accuracy

4

Double Double precision floating-point numbers with 14 digits of accuracy

8

Short Small integer in the range -32,768 to 32,767 2

Integer Whole numbers in the range -2,147,483,648 to +2,147,483,647

4

Long Larger whole numbers 8

String Alphanumeric data: letters, digits, and other characters

Varies

Object Any type of data 4

Page 3: Variables and Constants

Naming Variables and Constants

• Follow Visual Basic naming rules:

– must begin with a letter

– letters, digits, and underscores only (no spaces, periods)

– no reserved words such as Print or Class

• Follow naming conventions such as:

• use meaningful names , e.g. taxRate, not x

• include the data type in the name, e.g., countInteger

• use mixed case for variables and uppercase for constants quantityInteger or HOURLYRATEDecimal

Page 4: Variables and Constants

Declaring Variables

• Inside of a procedure:

Dim customerName As String

• Outside of a procedure:

Public totalCost As Decimal

Private numItems As Integer

• Ok to declare several variables at once:

Dim numMales, numFemales as Integer

Page 5: Variables and Constants

Declaring Constants

• Intrinsic Constants: built-in and ready to use:•Color.Red is predefined in Visual Basic

• Named Constants• Use Const keyword to declare

• Append a type declaration after the value: D=decimal, R=double, F=single, I=integer, L=long, S=short

Const SALES_TAX_RATE As Decimal = .07DConst NUM_STUDENTS As Integer = 100IConst COMPANY_ADDRESS As String = "101 Main Street"

Page 6: Variables and Constants

Scope of a Variable

• Scope of a variable means the how long the variable exists and can be used

• The scope may be:• Namespace – available to all procedures of a project; also called a global variable

• Module level – available to all procedures in a module (usually a form)

• Local – available to only the procedure where it’s declared

• Block level – available only within the block of code where it’s declared

Page 7: Variables and Constants

3-

Arithmetic Operations

Operator Operation Order () Group operations 1

^ Exponentiation 2

* / Multiplication/ Division 3

\ Integer Division 4

Mod Modulus – Remainder of division 5

+ - Addition/ Subtraction 6

“Please Excuse My Dear Aunt Sally”

3+4*2 = 11 Multiply then add(3+4)*2 = 14 Parentheses control: add then multiply8/4*2 = 4 Same level: left to right: divide then multiply

Page 8: Variables and Constants

Performing Arithmetic Operations in Visual Basic

• Calculations can be performed with variables and constants that contain numeric data

• Calculations cannot be performed on string data

• Remember: values from Text property of Text Boxes are strings, even if they contain numeric data. So …

– String data must be converted to a numeric data type before performing a calculation

– Numeric data must be converted back to strings before insertion into a text box.

Page 9: Variables and Constants

Example

Weight in Pounds: 5

Weight in Ounces: 80

Dim lbs, ozs As Integer

lbs = Integer.Parse(poundsTextBox.Text)

ozs = lbs*16

ouncesTextBox.Text = ozs.ToString()

•Parse() method fails if user enters nonnumeric data or leaves data blank.

Page 10: Variables and Constants

Assignment Statement in Visual Basic

• Form: variable = arithmetic operation

Write This: area = 3.14159 * radius ^ 2

Not This: 3.14159 * radius ^ 2 = area

• Shorthand Assignment: You can write

This: sum = sum + grade

Like This: sum += grade

• Other shorthand assignments:

+=, -=, *=, /=, \=, &=

Page 11: Variables and Constants

3-

Converting Between Numeric Data Types

• Implicit conversion

• Converts value from narrower data type to wider Example: Dim littleNum As Short

Dim bigNum As Long bigNum = littleNum

• Explicit conversion (casting)

• Uses methods of Convert class to convert between data types

• Example: Dim littleNum As Short Dim bigNum As Long bigNum = Convert.ToInt64(littleNum)

Page 12: Variables and Constants

Two Important Project Options in Visual Basic

• Option Explicit :variables must be declared before using. (Should always be on.)

• Option Strict: does not allow implicit conversions

•Makes VB a strongly typed language like C++, Java and C#

•Recommended to be turned on in the Project Properties menu.

Page 13: Variables and Constants

Formatting String Data for Display• To display numeric data in a label or text box, first convert

value to string using the ToString() method

• Add a formatting code to display things like:

• dollar signs, percent signs, and commas

• a specific number of digits that appear to right of decimal point

• a date in a specific format

• Example: Dim total As Decimal Dim stringTotal As String total = 1234.5678 stringTotal = total.ToString(“C”)

sets stringTotal to “$1,234.57”

Page 14: Variables and Constants

3-

Format Specifier Code Examples

Variable Value Code Output

totalDecimal 1125.6744 "C" $1,125.67

totalDecimal 1125.6744 "N0" 1,126

pinInteger 123 "D6" 000123

rateDecimal 0.075 "P" 7.50%

rateDecimal 0.075 "P3" 7.500%

rateDecimal 0.075 "P0" 8%

valueInteger -10 "C" ($10.00)

Page 15: Variables and Constants

Date Specifier Code Examples

Dim dt As Date

Dim dtString As String

dtString = dt.ToString(“d”)

Page 16: Variables and Constants

Handling Exceptions

• Exceptions - run-time errors that occur

• Error trapping - catching exceptions

• Error handling – writing code to deal with the exception

• The process is standardized in Visual Studio using try/ catch blocks.

– put code that might cause an exception in a Try block

– put code that handles the exception in a Catch block

Page 17: Variables and Constants

3-

Try/ Catch Blocks

Try‘statements that may cause an error

Catch [VariableName As ExceptionType]‘statements that handle the error

[Finally‘statements that always run in the Try block]

End Try

TryQuantity = Integer.Parse(QuantityTextBox.Text)QuantityTextBox.Text = Quantity.ToString()

CatchMessageLabel.Text = "Error in input data."

End Try

Page 18: Variables and Constants

3-

Try/Catch Block — Multiple Exceptions

TryScore = Integer.Parse(scoreTextBox.Text)

Total += Score Average = Total/ NumStudents

MessageLabel.Text = Average.ToString()Catch TheException As FormatException

MessageLabel.Text = "Error in input data.”Catch TheException As ArithmeticException

MessageLabel.Text = "Error in calculation.”Catch TheException As Exception MessageLabel.Text = “General Error.”Finally NumStudents += 1End Try

Page 19: Variables and Constants

MessageBox Object

• The MessageBox object is a popup window that displays information with various icons and buttons included.

• MessageBox.Show()is the method for displaying the message box.

• There are 21 different variations of the argument list to choose from (different combinations of parameters)

• IntelliSense displays argument lists, making the task of choosing the right one easier

Page 20: Variables and Constants

MessageBox.Show()

•Message – text to display in the box

•Title – text to display in the title bar

•Buttons – the set of buttons to include in the box•OK, OKCancel, RetryCancel, YesNo, YesNoCancel, AbortRetryIgnore

•Icons – the icon to display in the box•Asterisk, Error, Exclamation, Hand, Information, None, Question, Stop, Warning

MessageBox.Show(Message, Title, Buttons, Icon)

Page 21: Variables and Constants

Overloaded Methods

• MessageBox.Show()is an example of an overloaded method.

• Overloaded methods have more than one argument list that can be used to call the method.

• Each different argument list is called a signature.

• Supplied arguments must exactly match one of the signatures provided by the method (i.e. same number of arguments, same type of arguments, same order of the arguments).

• IntelliSense in Visual Studio editor helps when entering arguments so that they don’t need to be memorized.

Page 22: Variables and Constants

A Complete Example (Exercise 3.1, p. 149)

Create a form that lets the user enter for a food:

grams of fat, grams of carbohydrates, & grams of protein

When the user presses the Calculate button, to following is

displayed: 1. total calories for that food (1 gram of fat = 9

calories, 1 gram of carbs or protein = 4 calories),

2. total number of food entered so far

3. total calories of all the foods

Also add buttons for Clear, Print and Exit.

Catch any bad input data and display an appropriate message box.