Presentation is loading. Please wait.

Presentation is loading. Please wait.

Chapter 3: Variables, Constants, and Calculations

Similar presentations


Presentation on theme: "Chapter 3: Variables, Constants, and Calculations"— Presentation transcript:

1 Chapter 3: Variables, Constants, and Calculations
REV 01 Chapter 3: Variables, Constants, and Calculations Objectives Distinguish between variables, constants, and controls. Differentiate among the various data types. Apply naming conventions and indicating the data type. Declare variables and constants. Select the appropriate scope for a variable. Convert text input to numeric values. Perform calculations using variables and constants. Convert between numeric data types using implicit and explicit conversions. Round decimal values using the Decimal.Round method. Format values for output using the ToString method. Use Try/Catch blocks for error handling. Display message boxes with error messages. Accumulate sums and generate counts. DDC Programming III 1

2 Chapter 3: Data - Variables & Constants
REV 01 Variable 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 When you declare a variable or a named constant, VB reserves an area of memory and assigns it a name, called an identifier. Identifier names are specified according to the rules of Basic as well as some recommended naming conventions. DDC Programming III 2

3 Chapter 3: Data - Variables & Constants
REV 01 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 Example: ' Declare a string variable. Dim NameString As String DDC Programming III 3

4 Chapter 3: Data Types REV 01 Data Type Use For Storage Size in bytes
Boolean True or False value 2 Byte 0 to 255, binary data 1 Clear Single Unicode character 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 Short Small integer in the range -32,768 to 32,767 Integer Whole numbers in the range -2,147,483,648 to +2,147,483,647 Long Larger whole numbers String Alphanumeric data: letters, digits, and other characters Varies Object Any type of data The data type of a variable or constant indicates what type of information will be stored in the allocated memory space. The data type charts displays the kind of data each type of data types hold, and the amount of memory allocated. The most common types of variables and constants are String, Integer, and Decimal. DDC Programming III 4

5 Chapter 3: Naming Variables and Constants
REV 01 Chapter 3: Naming Variables and Constants Must follow Visual Basic Naming Rules Should follow Naming Conventions Meaningful names consisting of letters, digits, and underscores; must begin with a letter and no spaces or periods. Include class (data type) of variable (QUOTA_Integer) Use mixed case for variables and uppercase for constants (quantityInteger). Cannot use reserved words or keywords to which Basic has assigned a meaning, such as print, name, and value A programmer has to name (identify) the variables and named constants that will be used in a project. DDC Programming III 5

6 Chapter 3: Constants Named Intrinsic
REV 01 Chapter 3: Constants Named User assigned name, data type, and value Use CONST keyword to declare. Intrinsic System defined within Visual Studio Const COMPANY_ADDRESS_String As String = "101 S. Main Street" Const SALES_TAX_RATE_Decimal As Decimal = .08D Constants provide a way to use words to describe a value that doesn’t change. Constants are declared using the keyword and are given a name, a data type, and a value. Once a value is declared as a constant, its value can’t be changed during the execution of the project. Data type declared and data type of the value must match. Many sets of intrinsic constants (key term) are declared in system class libraries and are available for use in VB programs. DDC Programming III 6

7 Chapter 3: Assigning Values to Constants
REV 01 Chapter 3: Assigning Values to Constants Declare the data type of numeric constants by appending a type-declaration character. Decimal D Decimal – D Double R Double – R Integer I Integer – I Long L Long – L Short S Single F Single – F If a type-declaration character is not appended, any whole number is assumed to be Integer and any fractional value is assumed to be Double. Use two quotes with a string literal to avoid confusion. DDC Programming III 7

8 Chapter 3: Declaring Variables
REV 01 Chapter 3: 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. Inside a procedure you must use the Dim statement. Declaration Statements—General Form: Public|Private|Dim Identifier [As Datatype] DDC Programming III 8

9 Chapter 3: Declaration Statement Examples
REV 01 Chapter 3: Declaration Statement Examples Dim customerNameString As String Private totalSoldInteger As Integer Dim temperatureSingle As Single Dim priceDecimal As Decimal Private priceDecimal VB’s IntelliSense feature helps you enter Private, Public, and Dim statements—after you type the space that follows VariableName As, a list pops up and displays the possible entries for data type to complete the statement. If you begin to complete the statement the list automatically scrolls to the correct section; when the correct entry is highlighted press Enter, Tab, or the spacebar to select the entry, or double-click if using the mouse. The reserve word Dim is really short for dimension, which means size. When declaring a variable, the amount of memory reserved depends on its data type. DDC Programming III 9

10 Chapter 3: Scope and Lifetime of Variables
REV 01 Chapter 3: 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. A variable may exist and be visible for an entire project, for only one form, or for only one procedure. Visibility really means “this variable can be used or ‘seen’ in this location.” Namespace — Available to all procedures of project Module — Available to all procedures within that module (often a form) Use Public or Private keywords Local — Available only to the procedure in which it is declared Block — Available only in block of code inside a procedure where declared Previous versions of VB and some other programming languages refer to namespace variables as global variables. DDC Programming III 10

11 Chapter 3: Module Level Variable Declaration Example
REV 01 Chapter 3: Module Level Variable Declaration Example Code module-level declarations in the Declaration section at the top of the code. To enter module-level declarations, you must be in the Editor window at the top of your code. Place the Private and Const statements after the Class declaration but before your first procedure. DDC Programming III 11

12 Chapter 3: Calculations
REV 01 Chapter 3: 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 DDC Programming III 12

13 Chapter 3: Converting Strings to a Numeric Data Type
REV 01 Chapter 3: Converting Strings to a Numeric Data Type Use Parse methods to convert the Text property to its numeric form before it’s used in a calculation. 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. The class that you use depends on the data type of the variable to which you are assigning a value; for example, to convert text to an integer, use the Integer.Parse method, to convert to a decimal value, use Decimal.Parse. Pass the text string that you want to convert as an argument of the Parse method. Example: ' Convert input values to numeric variables. QuantityInteger = Integer.Parse(QuantityTextBox.Text) PriceDecimal = Decimal.Parse(PriceTextBox.Text) DDC Programming III 13

14 Chapter 3: Converting to String
REV 01 Chapter 3: Converting to String Values assigned to string variables or Text properties must be string. Convert any numeric data type to string using .ToString method. Examples: ResultTextBox.Text = ResultDecimal.ToString() CountTextBox.Text = CountInteger.ToString() IDString = IDInteger.ToString() When you assign a value to a variable, you must take care to assign like types; you assign an integer value to an Integer variable and a decimal value to a Decimal variable. There are some exceptions to the rule about assigning only like types — See “Implicit Conversions.” DDC Programming III 14

15 Chapter 3: Conversion Methods
REV 01 Chapter 3: Conversion Methods Method Convert To Integer.Parse Integer Decimal.Parse Decimal .ToString String DDC Programming III 15

16 Chapter 3: Conversion Examples
REV 01 Chapter 3: Conversion Examples QuantityInteger =Integer.Parse(quantityTextBox.Text) PriceDecimal =Decimal.Parse(priceTextBox.Text) WholeNumberInteger =Integer.Parse(digitString) ResultTextBox.Text =ResultDecimal.ToString( ) CountTextBox.Text =CountInteger.ToString( ) IDString =IDInteger.ToString( ) The Parse methods examine the value stored in the argument and attempts to convert it to a number in a process called parsing, which means to pick apart, character by character, and convert to another format. In case you need to convert to Long, Single, or Double, VB has a Parse method for each of those data type classes. DDC Programming III 16

17 Chapter 3: Arithmetic Operations
REV 01 Chapter 3: Arithmetic Operations Operator Operation + Addition – Subtraction * Multiplication / Division \ Integer Division Mod Modulus – Remainder of division ^ Exponentiation The arithmetic operations you can perform in VB include addition, subtraction, multiplication, division, integer division, modulus, and exponentiation. The first four operations are self explanatory, but you may not be familiar with Integer Division, Modulus, and/or exponentiation. Integer division — use to divide one integer by another giving an integer result, truncating (dropping) any remainder Modulus — returns the remainder of a division problem Exponentiation — raises a number to the power specified and returns (produces) a result of the Double data type. DDC Programming III 17

18 Chapter 3: Order of Operations
REV 01 Chapter 3: Order of Operations Hierarchy of operations, or 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 To change the order of evaluation, use parentheses. DDC Programming III 18

19 Chapter 3: Evaluation of Expression
1. All operations within parentheses. 2. All exponentiation. Multiple exponentiation operations are performed from left to right. 3. All multiplication and division. Multiple operations are performed from left to right. 4. All integer division. Multiple operations are performed from left to right. 5. Mod operations. Multiple operations are performed from left to right. 6. All addition and subtraction are performed from left to right. DDC Programming III

20 Chapter 3: Mathematical Examples
REV 01 Chapter 3: 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 DDC Programming III

21 Chapter 3: Using Calculations in Code
REV 01 Chapter 3: 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 — allows shorter versions of code =, +=, -=, *=, /=, \=, &= The assignment operators that you will use most often are += and – =. ‘Accumulate a total. TotalSalesDecimal += salesDecimal DDC Programming III 21

22 Chapter 3: Option Explicit and Option Strict
REV 01 Chapter 3: Option Explicit and Option Strict Option Explicit forces variables to be declared before using. Option Strict Makes VB a strongly typed language like C++, Java and C# 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 VB provides two options that can significantly change the behavior of the editor and compiler. Not using either Option Explicit and/or Option Strict can make coding somewhat easier, but provides opportunities for hard-to-find errors and very sloppy programming. When Option Explicit is turned off, programmers can use any variable name without first declaring it, which is a throwback to the older version of Basic and programmers spent many hours debugging programs that had small typos in a variable name. Programmers should always program with Option Explicit turned on-in VB.NET the option is turned on by default for all new projects. Programmers will need to place an additional code line before the first line of code in a file to turn it off. When Option Strict is turned on, the editor and compiler try to help keep programmers from making hard-to-find mistakes. DDC Programming III 22

23 Chapter 3: Converting Between Numeric Data Types
REV 01 Chapter 3: 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 Convert Class has methods that begin with “To” for each of the data types. In VB, you can convert data from one numeric data type to another—some conversions can be performed implicitly (automatically) and some you must specify explicitly. Implicit: Example: BigNumberDouble = SmallNumberInteger does not generate any error message, assuming that both variables are properly declared Explicit: Examples: NumberDecimal = Convert.ToDecimal(NumberSingle) ValueInteger = Convert.ToInt32(ValueDouble) DDC Programming III 23

24 Chapter 3: Performing Calculations with Unlike Data Types
REV 01 Chapter 3: Performing Calculations with Unlike Data Types VB performs the calculations using the wider data type. Use a cast if converting the result to a different data type. Eg: Convert.ToInt32(CountInteger / NumberDecimal) or Convert.ToSingle(CountInteger / NumberDecimal). VB does not convert to a different data type until it is necessary. The expression countInteger / 2* amount Decimal is evaluated as integer division for countInteger /2, producing an integer intermediate result; then the multiplication is performed on the integer and decimal value (amountDecimal), producing a decimal result. The methods of the Convert class use the CLR data types rather than the VB data types. Use Int32 for Integer, Int16 for Short, and Int64 for Long. DDC Programming III 24

25 Chapter 3: Rounding Numbers
REV 01 Chapter 3: Rounding Numbers Round decimal fractions Decimal.Round method returns a decimal result rounded to a specified number of decimal positions. Decimal.Round and Convert methods use technique called “rounding toward even.” See the Appendices for additional mathematical, financial, and string functions Example: ' Round to two decimal positions. ResultDecimal = Decimal.Round(AmountDecimal, 2) Decimal Value to Round Number of Decimal Positions Results 1,455 2 1.46 1.44 1.5 2.5 DDC Programming III 25

26 Chapter 3: Formatting Data for Display
REV 01 Chapter 3: 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 When wanting to display numeric data in the Text property of a label or text box, the value must first be converted to string—the data can be formatted, which controls the way the output will look. DisplayTextBox.Text = NumberInteger.ToString() DDC Programming III 26

27 Chapter 3: Using Format Specifier Codes
REV 01 Chapter 3: Using Format Specifier Codes "C" code Currency — String formatted with dollar sign, commas separating each group of 3 digits and 2 digits to the right of decimal point "N" code Number — String formatted with commas separating each group of 3 digits and 2 digits to the right of decimal point Can specify number of decimal positions Example: "C0" zero digits The format specifier codes format the display of output and are predefined. The default format of each of the formatting codes is based on the computer’s regional setting. Format specifier codes are displayed on the next slide (Slide 30) and examples are shown on the following slide (Slide 31). DDC Programming III 27

28 Chapter 3: Format Specifier Codes
REV 01 Chapter 3: Format Specifier Codes 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 DDC Programming III

29 Chapter 3: Format Specifier Code Examples
REV 01 Chapter 3: Format Specifier Code 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) DDC Programming III

30 Chapter 3: Date Specifier Code
REV 01 Chapter 3: Date Specifier Code Format DateTime values using format codes and ToString method. Date codes are case sensitive. You can use methods of the DateTime structure for formatting dates:ToLongDateString, ToShortDateString, ToLongTimeString, ToShortTimeString. See Appendix B or MSDN for additional information. DDC Programming III 30

31 Chapter 3: Handling Exceptions
REV 01 Chapter 3: Handling Exceptions Use structured exception handling to easily catch errors before run-time error occurs. Catching exceptions is referred to as error trapping. Coding to handle exception is called error handling. Error handling in Visual Studio.NET is standardized for all languages using the Common Language Runtime, CLR, which improves on previous versions of VB. When users input numbers and use those numbers in calculations, lots of things can go wrong—for example, the Parse methods, Integer.Parse and Decimal.Parse fail if the user enters nonnumeric data or leaves the text box blank. DDC Programming III 31

32 Chapter 3: Try/Catch Blocks
REV 01 Chapter 3: Try/Catch Blocks Enclose statements that might cause an error within Try/Catch block. If an exception occurs while statements in the Try block are executing, program 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. The Try-Block General Form is shown on the next slide (Slide 35). DDC Programming III 32

33 Chapter 3: Try Block - General Form
REV 01 Chapter 3: Try Block - General Form Try ‘statements that may cause an error Catch [VariableName As ExceptionType] ‘statements for action when an exception occurs [Finally ‘statements that always execute before exit of the Try block] End Try DDC Programming III

34 Chapter 3: Try Block - Example Catches Any Exception
REV 01 Chapter 3: Try Block - Example Catches Any Exception Try QuantityInteger = Integer.Parse(QuantityTextBox.Text) QuantityTextBox.Text = QuantityInteger.ToString( ) Catch MessageLabel.Text = "Error in input data." End Try The Catch will catch any exception. You also can specify the type of exception that you want to catch, and even write several Catch statements, each to catch a different type of exception. For example, you might want to display one message for bad input data and a different message for a calculation problem. DDC Programming III 34

35 Chapter 3: Try Block - Example Catches Specific Exception
REV 01 Chapter 3: Try Block - Example Catches Specific Exception This Catch statement catches bad input data that cannot be converted to numeric. To catch bad input data that cannot be converted to numeric, write the above Catch statement. Catch theException As FormatException MessageLabel.Text="Error in input data." End Try DDC Programming III 35

36 Chapter 3: Common Exception Classes
REV 01 Chapter 3: Common Exception Classes Each exception is an instance of the Exception class. The properties of this class allow you to determine the code location of the error, the type of error, and cause. *Refer to the Table 3.2 for Common Exception Classes examples. DDC Programming III 36

37 Chapter 3: Try Block - Example Handling Multiple Exceptions
REV 01 Chapter 3: Try Block - Example Handling Multiple Exceptions 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. If wanting to trap for more than one type of exception, multiple Catch blocks (handlers) can be included. When an exception occurs, the Catch statements are checked in sequence. DDC Programming III 37

38 Chapter 3: MessageBox Object
REV 01 Chapter 3: 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). Two sample message boxes created with the MessageBox clas. MessageBox.Show (TextMessage, TitlebarText, _ MessageBoxButtons, MesssageBoxIcon) DDC Programming III 38

39 Chapter 3: MessageBox Object
REV 01 Chapter 3: MessageBox Object 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 General Form: MessageBox.Show(TextMessage) MessageBox.Show(TextMessage, TitlebarText) MessageBox.Show(TextMessage, TitlebarText, MessageBoxButtons) MessageBox.Show(TextMessage, TitlebarText, MessageBoxButtons, MessageBoxIcon) DDC Programming III 39

40 Chapter 3: Using Overloaded Methods
REV 01 Chapter 3: Using Overloaded Methods This OOP feature allows the Show method to act differently for different arguments. Each argument list is called a signature so the Show method has several signatures. Supplied arguments must exactly match one of the signatures provided by the method. IntelliSense in Visual Studio editor helps when entering arguments so that they don’t need to be memorized. When you call the Show method, the arguments that you supply must exactly match one of the signatures provided by the method. DDC Programming III 40

41 Chapter 3: Testing Multiple Fields
REV 01 Chapter 3: Testing Multiple Fields Each input field presents an opportunity for an exception. To indicate specific fields that caused the exception, use nested Try/Catch blocks. Pinpoints specific errors, and after error, sets focus back to field in error Use SelectAll method of text box to make text appear selected to aid user. When you have more than one input field, each field presents an opportunity for an exception. DDC Programming III 41

42 Chapter 3: Counting & Accumulating Sums
REV 01 Chapter 3: Counting & 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 Programs often need to calculate the sum of numbers. The technique for summing is to declare a module-level variable for the total. If you want to count something, you need another module-level variable. To calculate an average, divide the sum of the items by the count of the items. Private saleCountInteger As Integer saleCountInteger += 1 AverageDiscountedSaleDecimal = DiscountedPriceSumDecimal / SaleCountInteger DDC Programming III 42


Download ppt "Chapter 3: Variables, Constants, and Calculations"

Similar presentations


Ads by Google