Download presentation
Presentation is loading. Please wait.
1
Chapter 3 Variables, Constants and Calculations
Programming In Visual Basic .NET
2
Data - Variables and Constants
Memory locations that hold data that can be changed during project execution Example: customer’s name Named Constant Memory locations that hold data that cannot be changed during project execution Example: sales tax rate © 2005 by The McGraw-Hill Companies, Inc. All rights reserved.
3
Data - Variables and Constants (continued)
In Visual Basic when you declare a Variable or Named Constant An area of memory is reserved A name is assigned called an Identifier Follow rules and naming conventions Use Declaration Statements to establish Variables and Constants Assign name and data type Not executable unless initialized on same line © 2005 by The McGraw-Hill Companies, Inc. All rights reserved.
4
Data Types (p 87 Table 3.1) Boolean Byte (0 to 255) Char Date String
Decimal Object Short (-32,768 to 32,767) Integer (-2,147,483,648 to 2,147,483,647) Long (larger whole numbers) Single (floating point accuracy to 6 digits) Double (floating point accuracy to 14 digits) © 2005 by The McGraw-Hill Companies, Inc. All rights reserved.
5
Data Types – Memory Usage
Boolean – 2 bytes Byte – 1 byte Char – 2 bytes Date – 8 bytes String – varies Decimal – 16 bytes Object – 4 bytes Short – 2 bytes Integer – 4 bytes Long – 8 bytes Single – 4 bytes Double – 8 bytes © 2005 by The McGraw-Hill Companies, Inc. All rights reserved.
6
Naming Variables and Constants
Must follow Visual Basic Naming Rules Should follow Naming Conventions Meaningful names Include class (data type) of variable Use mixed case for variables and uppercase for constants © 2005 by The McGraw-Hill Companies, Inc. All rights reserved.
7
Constants Named User assigned name, data type and value
Use CONST keyword to declare Intrinsic System defined within Visual Studio In Chapter 2 we used the Intrinsic Color Constants Const COMPANY_ADDRESS_String As String = "101 S. Main Street" Const SALES_TAX_RATE_Decimal As Decimal = .08D © 2005 by The McGraw-Hill Companies, Inc. All rights reserved.
8
Assigning Values to Constants
Declare the data type of numeric constants by appending a type-declaration character Decimal - D Double - R Integer - I Long - L Short - S Single - F Integer – I Single – F Decimal – D Double – R Long – L © 2005 by The McGraw-Hill Companies, Inc. All rights reserved.
9
Declaring Variables Declared inside a procedure using a Dim statement
Declared outside a procedure using Public, Private or Dim statements Always declare the variable’s data type May declare several variables with one statement Use IntelliSense to assist in writing statements © 2005 by The McGraw-Hill Companies, Inc. All rights reserved.
10
Declaration Examples Dim customerNameString As String
Private totalSoldInteger As Integer Dim temperatureSingle As Single Dim priceDecimal As Decimal Private priceDecimal As Decimal © 2005 by The McGraw-Hill Companies, Inc. All rights reserved.
11
Scope and Lifetime of Variables
Visibility of a variable is its scope Scope may be Namespace Module-level Local Block-level Lifetime of a variable is the period of time the variable exists © 2005 by The McGraw-Hill Companies, Inc. All rights reserved.
12
Scope and Lifetime of Variables (continued)
Namespace Available to all procedures of project Good programming practice excludes use of Namespace variables Module Available to all procedures within that module (often a form) Use Public or Private keywords Place in declaration section of module (form) Local Available only to the procedure it is declared in Declare with Dim keyword and place at top of procedure Block (not used until later in this course) Available only in block of code where declared © 2005 by The McGraw-Hill Companies, Inc. All rights reserved.
13
Module Level Variable Declaration Example
© 2005 by The McGraw-Hill Companies, Inc. All rights reserved.
14
Calculations Calculations can be performed with variables, constants, properties of certain objects, and numeric literals Do not use strings in calculations Values from Text property of Text Boxes Are strings, even if they contain numeric data Must be converted to a numeric data type before performing a calculation © 2005 by The McGraw-Hill Companies, Inc. All rights reserved.
15
Converting Strings to a Numeric Data Type
Use Parse methods to convert Text to numeric data Each numeric data type class has a Parse method Parse method returns a value that can be used in calculations Parse method fails if user enters nonnumeric data or leaves data blank © 2005 by The McGraw-Hill Companies, Inc. All rights reserved.
16
Converting to String Values assigned to string variables or Text properties must be string Convert any numeric data type to string using .ToString method © 2005 by The McGraw-Hill Companies, Inc. All rights reserved.
17
Method Convert To Conversion Methods Integer.Parse Integer
Decimal.Parse Decimal .ToString String © 2005 by The McGraw-Hill Companies, Inc. All rights reserved.
18
Conversion Examples quantityInteger = Integer.Parse(quantityTextBox.Text) priceDecimal = Decimal.Parse(priceTextBox.Text) wholeNumberInteger = Integer.Parse(digitString) resultLabel.Text = resultDecimal.ToString( ) countTextBox.Text = countInteger.ToString( ) idString = idInteger.ToString( ) © 2005 by The McGraw-Hill Companies, Inc. All rights reserved.
19
Arithmetic Operations
Operator Operation + Addition – Subtraction * Multiplication / Division \ Integer Division Mod Modulus – Remainder of division ^ Exponentiation © 2005 by The McGraw-Hill Companies, Inc. All rights reserved.
20
Order of Operations Order of precedence in arithmetic expressions from highest to lowest 1. Any operation inside parentheses 2. Exponentiation 3. Multiplication and division 4. Integer division 5. Modulus 6. Addition and subtraction © 2005 by The McGraw-Hill Companies, Inc. All rights reserved.
21
Mathematical Examples
Note the use of parentheses to control order of precedence 3+4*2 = 11 Multiply then add (3+4)*2 = 14 Parentheses control: add then multiply 8/4*2 = 4 Same level, left to right: divide then multiply © 2005 by The McGraw-Hill Companies, Inc. All rights reserved.
22
Using Calculations in Code
Perform calculations in assignment statements What appears on right side of assignment operator is assigned to item on left side Assignment operators =, +=, -=, *=, /=, \=, &= © 2005 by The McGraw-Hill Companies, Inc. All rights reserved.
23
Option Explicit and Option Strict
Option Explicit forces variables to be declared before using Option Strict Makes VB a strongly typed language Does not allow implicit conversions from a wider data type to a narrower one or between String and numeric data types Best practice to always turn on either in code or in Project Properties dialog box © 2005 by The McGraw-Hill Companies, Inc. All rights reserved.
24
Converting Between Numeric Data Types
Implicit (automatic) conversion Converts value from narrower data type to wider type where no danger of losing precision exists Explicit conversion (casting) Uses methods of Convert class to convert between data types ToDecimal, ToSingle, ToDouble, ToInt16 (Short), ToInt32 (Integer), ToInt64 (Long) © 2005 by The McGraw-Hill Companies, Inc. All rights reserved.
25
Rounding Numbers Round decimal fractions Use Decimal.Round method
Decimal.Round and Convert methods use technique called “rounding toward even” See Appendix B for additional mathematical, financial and string functions © 2005 by The McGraw-Hill Companies, Inc. All rights reserved.
26
Formatting Data for Display
To display numeric data in a label or text box, first convert value to string Use ToString method Format the data using formatting codes Specifies use of dollar sign, percent sign and commas Specifies number of digits that appear to right of decimal point resultLabel.Text = resultDecimal.ToString( ) countTextBox.Text = countInteger.ToString( ) © 2005 by The McGraw-Hill Companies, Inc. All rights reserved.
27
Using Format Specifier Codes
"C" code Currency – String formatted with dollar sign, commas separating each group of three digits and two digits to the right of decimal point "N" code Number – String formatted with commas separating each group of three digits and two digits to the right of decimal point Can specify number of decimal positions Example: "C0" zero digits © 2005 by The McGraw-Hill Companies, Inc. All rights reserved.
28
Format Specifier Codes
Name C or c Currency F or f Fixed-point N or n Number D or d Digits P or p Percent © 2005 by The McGraw-Hill Companies, Inc. All rights reserved.
29
Format Specifier Codes Examples
Variable Value Code Output totalDecimal "C" $1,125.67 "N0" 1,126 pinInteger 123 "D6" 000123 rateDecimal 0.075 "P" 7.50% "P3" 7.500% "P0" 8% valueInteger -10 ($10.00) © 2005 by The McGraw-Hill Companies, Inc. All rights reserved.
30
Date Specifier Code Format DateTime values using format codes and ToString method Date codes are case sensitive d Short date D Long date t Short time T Long time f Full date/time F Full date/time g General (short time) G General (long time) M or m Month R or r GMT pattern ToLongDateString, ToShortDateString, ToLongTimeString, ToShortTimeString methods also available © 2005 by The McGraw-Hill Companies, Inc. All rights reserved.
31
Handling Exceptions Use structured exception handling to catch errors before run-time error occurs Catching exceptions referred to as error trapping Code to handle exception called error handling Error handling in Visual Studio .NET is standardized for all languages using the CLR © 2005 by The McGraw-Hill Companies, Inc. All rights reserved.
32
Try/Catch Blocks Enclose statements that might cause an error within Try/Catch block If an error occurs control is transferred to the Catch Block If a Finally statement is included, the code in that section executes last, whether or not an exception occurred © 2005 by The McGraw-Hill Companies, Inc. All rights reserved.
33
Try Block - General Form
statements that may cause error Catch [VariableName As ExceptionType] statements for action when an exception occurs [Finally statements that always execute before exit of Try block] End Try See page 114 for list of common Exception Classes © 2005 by The McGraw-Hill Companies, Inc. All rights reserved.
34
Try Block - Example Catches Any Exception
quantityInteger = Integer.Parse(quantityTextBox.Text) quantityLabel.Text = quantityInteger.ToString( ) Catch messageLabel.Text = "Error in input data." End Try © 2005 by The McGraw-Hill Companies, Inc. All rights reserved.
35
Try Block - Example Catches Specific Exception
quantityInteger = Integer.Parse(quantityTextBox.Text) quantityLabel.Text = quantityInteger.ToString( ) Catch theException As FormatException messageLabel.Text="Error in input data." End Try Failure of numeric conversion, usually blank or nonnumeric data © 2005 by The McGraw-Hill Companies, Inc. All rights reserved.
36
Try Block - Example Handling Multiple Exceptions
' Statements that may cause errors. Catch theException As FormatException ' Statements for nonnumeric data. Catch theException As ArithmeticException ' Statements for calculation problem. Catch theException As Exception ' Statements for any other exception. End Try © 2005 by The McGraw-Hill Companies, Inc. All rights reserved.
37
Displaying Messages in Message Boxes
Use Show method of MessageBox to display message box, a special type of window Arguments of Show method Message to display Optional Title Bar Caption Optional Button(s) Optional Icon © 2005 by The McGraw-Hill Companies, Inc. All rights reserved.
38
MessageBox Object The MessageBox is an overloaded method Signatures correspond to the argument list There are multiple signatures to choose from Do not reverse, transpose or leave out any of the arguments IntelliSense displays argument list (also called signatures) MessageBox.Show (TextMessage, TitlebarText, _ MessageBoxButtons, MesssageBoxIcon) © 2005 by The McGraw-Hill Companies, Inc. All rights reserved.
39
MessageBox Object (continued)
TextMessage string String literal or variable that displays message Title Bar text String that appears in title bar of message box MessageBox Buttons OK, OKCancel, RetryCancel, YesNo, YesNoCancel, AbortRetryIgnore MessageBox Icons Asterisk, Error, Exclamation, Hand, Information, None, Question, Stop, Warning © 2005 by The McGraw-Hill Companies, Inc. All rights reserved.
40
Testing Multiple Fields
Each input field presents a chance for an error To indicate specific field that caused error use nested Try/Catch blocks After error set focus back to field in error Use SelectAll method of text box to make text appear selected to aid user © 2005 by The McGraw-Hill Companies, Inc. All rights reserved.
41
Counting and Accumulating Sums
Declare module-level variables, since local level variables reset to 0 each time the procedure is called Summing Numbers Counting Calculating an Average discountedPriceSumDecimal += discountedPriceDecimal Private saleCountInteger As Integer saleCountInteger += 1 averageDiscountedSaleDecimal = discountedPriceSumDecimal / saleCountInteger © 2005 by The McGraw-Hill Companies, Inc. All rights reserved.
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.