aslkjdhfalskhjfgalsdkfhalskdhjfglaskdhjflaskdhjfglaksjdhflakshflaksdhjfglaksjhflaksjhf aslkjdhfalskhjfgalsdkfhalskdhjfglas...
Variables, Constants and Calculations Chapter 3 McGraw-Hill © 2006 The McGraw-Hill Companies, Inc. All rights reserved.
Objectives  (1 of 2) <ul><li>Distinguish between  variables ,  constants , and controls </li></ul><ul><li>Differentiate am...
Objectives  (2 of 2) <ul><li>Perform calculations using variables and constants </li></ul><ul><li>Convert between numeric ...
Data - Variables and Constants  (1 of 2) <ul><li>Variable </li></ul><ul><ul><li>Memory locations that hold data that  can ...
Data - Variables and Constants  (2 of 2) <ul><li>In Visual Basic when you declare a Variable or Named Constant  </li></ul>...
Data Types   4 Any type of data Object Varies Alphanumeric data: letters, digits, and other characters String 8 Larger who...
Naming Variables and Constants <ul><li>Must follow Visual Basic Naming Rules </li></ul><ul><li>Should follow Naming Conven...
Constants <ul><li>Named </li></ul><ul><ul><li>User assigned name, data type and value </li></ul></ul><ul><ul><li>Use CONST...
Assigning Values to Constants <ul><li>Declare the data type of numeric constants by appending a type-declaration character...
Declaring Variables <ul><li>Declared inside a procedure using a Dim statement </li></ul><ul><li>Declared outside a procedu...
Declaration Statement Examples As Decimal Private priceDecimal As Decimal Dim priceDecimal As Single Dim temperatureSingle...
Scope and Lifetime of Variables  (1 of 2) <ul><li>Visibility of a variable is its scope </li></ul><ul><li>Scope may be </l...
Module Level Variable Declaration Example Code module-level declarations in the Declaration section at the top of the code
Calculations <ul><li>Calculations can be performed with variables, constants, properties of certain objects, and numeric l...
Converting Strings to a Numeric Data Type <ul><li>Use Parse methods to convert  the Text property to its numeric form befo...
Converting to String <ul><li>Values assigned to string variables or Text properties must be string </li></ul><ul><li>Conve...
Conversion Methods <ul><ul><li>Method Convert To </li></ul></ul><ul><ul><li>Integer.Parse Integer </li></ul></ul><ul><ul><...
Conversion Examples quantityInteger  =Integer.Parse(quantityTextBox.Text) priceDecimal   =Decimal.Parse(priceTextBox.Text)...
Arithmetic Operations <ul><ul><li>Operator Operation </li></ul></ul><ul><ul><li>+ Addition </li></ul></ul><ul><ul><li>– Su...
Order of Operations <ul><li>Hierarchy of operations, or  order of precedence , in arithmetic expressions from highest to l...
Evaluation of Expression <ul><li>1. All operations within parentheses. Multiple operations within the parentheses are perf...
Mathematical Examples <ul><li>Note the use of parentheses to control order of precedence </li></ul>3+4*2 = 11 Multiply the...
Using Calculations in Code <ul><li>Perform calculations in assignment statements </li></ul><ul><li>What appears on right s...
Option Explicit and Option Strict <ul><li>Option Explicit  forces variables to be declared before using </li></ul><ul><li>...
Converting Between Numeric Data Types <ul><li>Implicit (automatic) conversion </li></ul><ul><ul><li>Converts value from na...
Performing Calculations with  Unlike Data Types <ul><li>VB performs the calculations using the wider data type </li></ul><...
Rounding Numbers <ul><li>Round decimal fractions </li></ul><ul><ul><li>Decimal.Round method returns a decimal result round...
Formatting Data for Display <ul><li>To display numeric data in a label or text box, first convert value to string </li></u...
Using Format Specifier Codes <ul><li>&quot; C &quot;  code </li></ul><ul><ul><li>Currency – String formatted with dollar s...
Format Specifier Codes Percent P or p Digits D or d Number N or n Fixed-point F or f Currency C or c Name Format Specifier...
Format Specifier Code Examples ($10.00) &quot;C&quot; -10 valueInteger 8% &quot;P0&quot; 0.075 rateDecimal 7.500% &quot;P3...
Date Specifier Code <ul><li>Format DateTime values using format codes and ToString method </li></ul><ul><li>Date codes are...
Handling Exceptions <ul><li>Use structured  exception  handling to easily catch errors before run-time error occurs </li><...
Try/Catch Blocks <ul><li>Enclose statements that might cause an error within Try/Catch block </li></ul><ul><ul><li>If an e...
Try Block - General Form Try statements that may cause error Catch  [VariableName As ExceptionType] statements for action ...
Try Block - Example Catches Any Exception Try quantityInteger = Integer.Parse(quantityTextBox.Text) Me.quantityLabel.Text ...
Try Block - Example Catches Specific Exception <ul><li>This Catch statement catches bad input data that cannot be converte...
Common Exception Classes Each exception is an instance of the Exception class. The properties of this class allow you to d...
Try Block - Example Handling Multiple Exceptions Try '   Statements that may cause errors. Catch   theException As FormatE...
MessageBox Object  (1 of 2) <ul><li>The MessageBox is an overloaded method </li></ul><ul><ul><li>Signatures  correspond to...
MessageBox Object   (2 of 2) <ul><li>TextMessage string </li></ul><ul><ul><li>String literal  or variable that displays me...
Using Overloaded Methods <ul><li>This OOP feature allows the Show method to act differently for different arguments </li><...
Testing Multiple Fields <ul><li>Each input field presents an opportunity for an exception </li></ul><ul><li>To indicate sp...
Counting and Accumulating Sums <ul><li>Declare module-level variables, since local level variables reset to 0 each time th...
Upcoming SlideShare
Loading in …5
×

Chapter 03

1,157 views

Published on

Published in: Education, Sports, Technology
0 Comments
1 Like
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total views
1,157
On SlideShare
0
From Embeds
0
Number of Embeds
7
Actions
Shares
0
Downloads
15
Comments
0
Likes
1
Embeds 0
No embeds

No notes for slide
  • Brief description on how to navigate within this presentation (ppt) The first time a Key Term from the chapter is used in the ppt it will display in blue Gold colored text boxes display coding examples Slides will be numbered (# of #) when multiple slides on same topic (Slide title) Speaker notes are included where appropriate for slides (*)Denotes either a comment for page reference to textbook or slide reference in ppt
  • 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
  • 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 for each
  • A programmer has to name (identify) the variables and named constants that will be used in a project
  • 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
  • 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
  • VB 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 dimension, which means size. When declaring a variable, the amount of memory reserved depends on its data type.
  • 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 An example of a module level variable declaration is displayed on the next slide (Slide 15)
  • 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
  • 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 ( chart shown on next slide, Slide 19) There are some exception to the rule about assigning only like types See “Implicit Conversions”
  • The arithmetic operations you can perform 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 pwer specified and retruns (produces) a result of the Double data type
  • 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 provide 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 a an additional code line before the first line of code in a file to turn it off When Option Strict it turned on, the editor and compiler try to help keep programmers from making hard-to-find mistakes. By having Option Strict turned on programmers can be saved from developing poor programming habits
  • 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. *Refer to p. 114 for tables displaying Conversion examples
  • 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
  • See the Appendices for additional mathematical, financial and string functions
  • 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
  • The format specifier codes formats 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 32) and examples are shown on the following slide (Slide 33)
  • The strings returned are based on the computer’s regional settings and can be changed. Currently the default values are set for US-English in Windows XP *Refer to chart on p. 118
  • 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
  • The Try-Block General Form is shown on the next slide (Slide 37)
  • *Refer to the chart on p. 125 for Common Exception Classes examples
  • 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.
  • Two sample message boxes
  • Programs often need to calculate the sum of numbers. The technique for summing is to declare a module-level variable for the total
  • Chapter 03

    1. 1. aslkjdhfalskhjfgalsdkfhalskdhjfglaskdhjflaskdhjfglaksjdhflakshflaksdhjfglaksjhflaksjhf aslkjdhfalskhjfgalsdkfhalskdhjfglaskdhjflaskdhjfglaksjdhflakshflaksdhjfglaksjhflaksjhf aslkjdhfalskhjfgalsdkfhalskdhjfglaskdhjflaskdhjfglaksjdhflakshflaksdhjfglaksjhflaksjhf aslkjdhfalskhjfgalsdkfhalskdhjfglaskdhjflaskdhjfglaksjdhflakshflaksdhjfglaksjhflaksjhf aslkjdhfalskhjfgalsdkfhalskdhjfglaskdhjflaskdhjfglaksjdhflakshflaksdhjfglaksjhflaksjhf aslkjdhfalskhjfgalsdkfhalskdhjfglaskdhjflaskdhjfglaksjdhflakshflaksdhjfglaksjhflaksjhf aslkjdhfalskhjfgalsdkfhalskdhjfglaskdhjflaskdhjfglaksjdhflakshflaksdhjfglaksjhflaksjhf aslkjdhfalskhjfgalsdkfhalskdhjfglaskdhjflaskdhjfglaksjdhflakshflaksdhjfglaksjhflaksjhf aslkjdhfalskhjfgalsdkfhalskdhjfglaskdhjflaskdhjfglaksjdhflakshflaksdhjfglaksjhflaksjhf aslkjdhfalskhjfgalsdkfhalskdhjfglaskdhjflaskdhjfglaksjdhflakshflaksdhjfglaksjhflaksjhf aslkjdhfalskhjfgalsdkfhalskdhjfglaskdhjflaskdhjfglaksjdhflakshflaksdhjfglaksjhflaksjhf aslkjdhfalskhjfgalsdkfhalskdhjfglaskdhjflaskdhjfglaksjdhflakshflaksdhjfglaksjhflaksjhf aslkjdhfalskhjfgalsdkfhalskdhjfglaskdhjflaskdhjfglaksjdhflakshflaksdhjfglaksjhflaksjhf aslkjdhfalskhjfgalsdkfhalskdhjfglaskdhjflaskdhjfglaksjdhflakshflaksdhjfglaksjhflaksjhf aslkjdhfalskhjfgalsdkfhalskdhjfglaskdhjflaskdhjfglaksjdhflakshflaksdhjfglaksjhflaksjhf aslkjdhfalskhjfgalsdkfhalskdhjfglaskdhjflaskdhjfglaksjdhflakshflaksdhjfglaksjhflaksjhf aslkjdhfalskhjfgalsdkfhalskdhjfglaskdhjflaskdhjfglaksjdhflakshflaksdhjfglaksjhflaksjhf aslkjdhfalskhjfgalsdkfhalskdhjfglaskdhjflaskdhjfglaksjdhflakshflaksdhjfglaksjhflaksjhf aslkjdhfalskhjfgalsdkfhalskdhjfglaskdhjflaskdhjfglaksjdhflakshflaksdhjfglaksjhflaksjhf aslkjdhfalskhjfgalsdkfhalskdhjfglaskdhjflaskdhjfglaksjdhflakshflaksdhjfglaksjhflaksjhf aslkjdhfalskhjfgalsdkfhalskdhjfglaskdhjflaskdhjfglaksjdhflakshflaksdhjfglaksjhflaksjhf aslkjdhfalskhjfgalsdkfhalskdhjfglaskdhjflaskdhjfglaksjdhflakshflaksdhjfglaksjhflaksjhf aslkjdhfalskhjfgalsdkfhalskdhjfglaskdhjflaskdhjfglaksjdhflakshflaksdhjfglaksjhflaksjhf aslkjdhfalskhjfgalsdkfhalskdhjfglaskdhjflaskdhjfglaksjdhflakshflaksdhjfglaksjhflaksjhf
    2. 2. Variables, Constants and Calculations Chapter 3 McGraw-Hill © 2006 The McGraw-Hill Companies, Inc. All rights reserved.
    3. 3. Objectives (1 of 2) <ul><li>Distinguish between variables , constants , and controls </li></ul><ul><li>Differentiate among the various data types </li></ul><ul><li>Apply naming conventions incorporating standards and indicating the data type </li></ul><ul><li>Declare variables and constants </li></ul><ul><li>Select the appropriate scope for a variable </li></ul><ul><li>Convert text input to numeric values </li></ul>
    4. 4. Objectives (2 of 2) <ul><li>Perform calculations using variables and constants </li></ul><ul><li>Convert between numeric data types using implicit and explicit conversions </li></ul><ul><li>Round decimal values using the Decimal.Round method </li></ul><ul><li>Format values for output using the ToString method. </li></ul><ul><li>Use Try/Catch blocks for error handling </li></ul><ul><li>Display message boxes with error messages </li></ul><ul><li>Accumulate sums and generate counts </li></ul>
    5. 5. Data - Variables and Constants (1 of 2) <ul><li>Variable </li></ul><ul><ul><li>Memory locations that hold data that can be changed during project execution </li></ul></ul><ul><ul><li>Example: customer’s name </li></ul></ul><ul><li>Named Constant </li></ul><ul><ul><li>Memory locations that hold data that cannot be changed during project execution </li></ul></ul><ul><ul><li>Example: sales tax rate </li></ul></ul>
    6. 6. Data - Variables and Constants (2 of 2) <ul><li>In Visual Basic when you declare a Variable or Named Constant </li></ul><ul><ul><li>An area of memory is reserved </li></ul></ul><ul><ul><li>A name is assigned called an Identifier </li></ul></ul><ul><ul><li>Follow rules and naming conventions </li></ul></ul><ul><li>Use Declaration Statements to establish Variables and Constants </li></ul><ul><ul><li>Assign name and data type </li></ul></ul><ul><ul><li>Not executable unless initialized on same line </li></ul></ul>
    7. 7. Data Types 4 Any type of data Object Varies Alphanumeric data: letters, digits, and other characters String 8 Larger whole numbers Long 4 Whole numbers in the range -2,147,483,648 to +2,147,483,647 Integer 2 Small integer in the range -32,768 to 32,767 Short 8 Double precision floating-point numbers with 14 digits of accuracy Double 4 Single precision floating-point numbers with six digits of accuracy Single 16 Decimal fractions, such as dollars/cents Decimal 8 1/1/0001 through 12/31/9999 Date 2 Single Unicode character Clear 1 0 to 255, binary data Byte 2 True or False value Boolean Storage Size in bytes Use For Data Type
    8. 8. Naming Variables and Constants <ul><li>Must follow Visual Basic Naming Rules </li></ul><ul><li>Should follow Naming Conventions </li></ul><ul><ul><li>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) </li></ul></ul><ul><ul><li>Use mixed case for variables and uppercase for constants (quantityInteger) </li></ul></ul><ul><ul><li>Can not use reserved words or keywords that Basic has assigned a meaning such as print, name, and value </li></ul></ul>
    9. 9. Constants <ul><li>Named </li></ul><ul><ul><li>User assigned name, data type and value </li></ul></ul><ul><ul><li>Use CONST keyword to declare </li></ul></ul><ul><li>Intrinsic </li></ul><ul><ul><li>System defined within Visual Studio </li></ul></ul>Const COMPANY_ADDRESS_String As String = &quot;101 S. Main Street&quot; Const SALES_TAX_RATE_Decimal As Decimal = .08D
    10. 10. Assigning Values to Constants <ul><li>Declare the data type of numeric constants by appending a type-declaration character </li></ul>Single – 101.25F F Single S Short Long – 134257987L L Long Integer – 12345678I I Integer Double – 52875.8R R Double Decimal – 850.50D D Decimal
    11. 11. Declaring Variables <ul><li>Declared inside a procedure using a Dim statement </li></ul><ul><li>Declared outside a procedure using Public, Private or Dim statements </li></ul><ul><li>Always declare the variable’s data type </li></ul><ul><li>May declare several variables with one statement </li></ul><ul><li>Use IntelliSense to assist in writing statements </li></ul>
    12. 12. Declaration Statement Examples As Decimal Private priceDecimal As Decimal Dim priceDecimal As Single Dim temperatureSingle As Integer Private totalSoldInteger As Integer As String Dim customerName Strging As String
    13. 13. Scope and Lifetime of Variables (1 of 2) <ul><li>Visibility of a variable is its scope </li></ul><ul><li>Scope may be </li></ul><ul><ul><li>Namespace </li></ul></ul><ul><ul><li>Module level </li></ul></ul><ul><ul><li>Local </li></ul></ul><ul><ul><li>Block level </li></ul></ul><ul><li>Lifetime of a variable is the period of time the variable exists </li></ul>
    14. 14. Module Level Variable Declaration Example Code module-level declarations in the Declaration section at the top of the code
    15. 15. Calculations <ul><li>Calculations can be performed with variables, constants, properties of certain objects, and numeric literals </li></ul><ul><li>Do not use strings in calculations </li></ul><ul><li>Values from Text property of Text Boxes </li></ul><ul><ul><li>Are strings, even if they contain numeric data </li></ul></ul><ul><ul><li>Must be converted to a numeric data type before performing a calculation </li></ul></ul>
    16. 16. Converting Strings to a Numeric Data Type <ul><li>Use Parse methods to convert the Text property to its numeric form before it’s used in a calculation </li></ul><ul><li>Each numeric data type class has a Parse method </li></ul><ul><li>Parse method returns a value that can be used in calculations </li></ul><ul><li>Parse method fails if user enters nonnumeric data or leaves data blank </li></ul>
    17. 17. Converting to String <ul><li>Values assigned to string variables or Text properties must be string </li></ul><ul><li>Convert any numeric data type to string using .ToString method </li></ul>
    18. 18. Conversion Methods <ul><ul><li>Method Convert To </li></ul></ul><ul><ul><li>Integer.Parse Integer </li></ul></ul><ul><ul><li>Decimal.Parse Decimal </li></ul></ul><ul><ul><li>.ToString String </li></ul></ul>
    19. 19. 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( )
    20. 20. Arithmetic Operations <ul><ul><li>Operator Operation </li></ul></ul><ul><ul><li>+ Addition </li></ul></ul><ul><ul><li>– Subtraction </li></ul></ul><ul><ul><li>* Multiplication </li></ul></ul><ul><ul><li>/ Division </li></ul></ul><ul><ul><li> Integer Division </li></ul></ul><ul><ul><li>Mod Modulus – Remainder of division </li></ul></ul><ul><ul><li>^ Exponentiation </li></ul></ul>
    21. 21. Order of Operations <ul><li>Hierarchy of operations, or order of precedence , in arithmetic expressions from highest to lowest </li></ul><ul><ul><ul><li>1. Any operation inside parentheses </li></ul></ul></ul><ul><ul><ul><li>2. Exponentiation </li></ul></ul></ul><ul><ul><ul><li>3. Multiplication and division </li></ul></ul></ul><ul><ul><ul><li>4. Integer division </li></ul></ul></ul><ul><ul><ul><li>5. Modulus </li></ul></ul></ul><ul><ul><ul><li>6. Addition and subtraction </li></ul></ul></ul>
    22. 22. Evaluation of Expression <ul><li>1. All operations within parentheses. Multiple operations within the parentheses are performed according to the rules of precedence. </li></ul><ul><li>2. All exponentiation. Multiple exponentiation operations are performed from left to right. </li></ul><ul><li>3. All multiplication and division. Multiple operations are performed from left to right. </li></ul><ul><li>4. All integer division. Multiple operations are performed from left to right. </li></ul><ul><li>5. Mod operations. Multiple operations are performed from left to right. </li></ul><ul><li>6. All addition and subtraction are performed from left to right. </li></ul>
    23. 23. Mathematical Examples <ul><li>Note the use of parentheses to control order of precedence </li></ul>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
    24. 24. Using Calculations in Code <ul><li>Perform calculations in assignment statements </li></ul><ul><li>What appears on right side of assignment operator is assigned to item on left side </li></ul><ul><li>Assignment operators – allows shorter versions of code =, +=, -=, *=, /=, =, &= </li></ul>‘ Accumulate a total. TotalSalesDecimal += salesDecimal
    25. 25. Option Explicit and Option Strict <ul><li>Option Explicit forces variables to be declared before using </li></ul><ul><li>Option Strict </li></ul><ul><ul><li>Makes VB a strongly typed language like C++, Java and C# </li></ul></ul><ul><ul><li>Does not allow implicit conversions from a wider data type to a narrower one or between String and numeric data types </li></ul></ul><ul><ul><li>Best practice to always turn on either in code or in Project Properties dialog box </li></ul></ul>
    26. 26. Converting Between Numeric Data Types <ul><li>Implicit (automatic) conversion </li></ul><ul><ul><li>Converts value from narrower data type to wider type where no danger of losing precision exists </li></ul></ul><ul><li>Explicit conversion ( casting ) </li></ul><ul><ul><li>Uses methods of Convert class to convert between data types </li></ul></ul><ul><ul><li>Convert Class has methods that begin with “To” for each of the data types </li></ul></ul>
    27. 27. Performing Calculations with Unlike Data Types <ul><li>VB performs the calculations using the wider data type </li></ul><ul><li>Perform a cast if converting the result to a different data type </li></ul><ul><li>VB does not convert to a different data type until it is necessary </li></ul>
    28. 28. Rounding Numbers <ul><li>Round decimal fractions </li></ul><ul><ul><li>Decimal.Round method returns a decimal result rounded to a specified number of decimal positions </li></ul></ul><ul><ul><li>Decimal.Round and Convert methods use technique called “rounding toward even” </li></ul></ul>2 0 2.5 2 0 1.5 1.44 2 1,455 1.46 2 1,455 Results Number of Decimal Positions Decimal Value to Round
    29. 29. Formatting Data for Display <ul><li>To display numeric data in a label or text box, first convert value to string </li></ul><ul><ul><li>Use ToString method </li></ul></ul><ul><li>Format the data using formatting codes </li></ul><ul><ul><li>Specifies use of dollar sign, percent sign and commas </li></ul></ul><ul><ul><li>Specifies number of digits that appear to right of decimal point </li></ul></ul>Me.displayTextBox.Text = numberInteger.ToString()
    30. 30. Using Format Specifier Codes <ul><li>&quot; C &quot; code </li></ul><ul><ul><li>Currency – String formatted with dollar sign, commas separating each group of 3 digits and 2 digits to the right of decimal point </li></ul></ul><ul><li>&quot; N &quot; code </li></ul><ul><ul><li>Number – String formatted with commas separating each group of 3 digits and 2 digits to the right of decimal point </li></ul></ul><ul><li>Can specify number of decimal positions </li></ul><ul><ul><li>Example: &quot; C0 &quot; zero digits </li></ul></ul>
    31. 31. Format Specifier Codes Percent P or p Digits D or d Number N or n Fixed-point F or f Currency C or c Name Format Specifier Codes
    32. 32. Format Specifier Code Examples ($10.00) &quot;C&quot; -10 valueInteger 8% &quot;P0&quot; 0.075 rateDecimal 7.500% &quot;P3&quot; 0.075 rateDecimal 7.50% &quot;P&quot; 0.075 rateDecimal 000123 &quot;D6&quot; 123 pinInteger 1,126 &quot;N0&quot; 1125.6744 totalDecimal $1,125.67 &quot;C&quot; 1125.6744 totalDecimal Output Code Value Variable
    33. 33. Date Specifier Code <ul><li>Format DateTime values using format codes and ToString method </li></ul><ul><li>Date codes are case sensitive </li></ul>
    34. 34. Handling Exceptions <ul><li>Use structured exception handling to easily catch errors before run-time error occurs </li></ul><ul><li>Catching exceptions referred to as error trapping </li></ul><ul><li>Coding to handle exception called error handling </li></ul><ul><li>Error handling in Visual Studio.NET is standardized for all languages using the Common Language Runtime, CLR, which improves on previous versions of VB </li></ul>
    35. 35. Try/Catch Blocks <ul><li>Enclose statements that might cause an error within Try/Catch block </li></ul><ul><ul><li>If an exception occurs while statements in the Try block are executing, program control is transferred to the Catch Block </li></ul></ul><ul><ul><li>If a Finally statement is included, the code in that section executes last, whether or not an exception occurred </li></ul></ul>
    36. 36. Try Block - General Form Try 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
    37. 37. Try Block - Example Catches Any Exception Try quantityInteger = Integer.Parse(quantityTextBox.Text) Me.quantityLabel.Text = quantityInteger.ToString( ) Catch Me.messageLabel.Text = &quot;Error in input data.&quot; End Try
    38. 38. Try Block - Example Catches Specific Exception <ul><li>This Catch statement catches bad input data that cannot be converted to numeric </li></ul>Catch theException As FormatException messageLabel.Text=&quot;Error in input data.&quot; End Try
    39. 39. 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.
    40. 40. Try Block - Example Handling Multiple Exceptions Try ' 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
    41. 41. MessageBox Object (1 of 2) <ul><li>The MessageBox is an overloaded method </li></ul><ul><ul><li>Signatures correspond to the argument list </li></ul></ul><ul><ul><li>There are multiple signatures to choose from </li></ul></ul><ul><ul><li>Do not reverse, transpose or leave out any of the arguments </li></ul></ul><ul><ul><li>IntelliSense displays argument list (also called signatures) </li></ul></ul>MessageBox.Show (TextMessage, TitlebarText, _ MessageBoxButtons, MesssageBoxIcon)
    42. 42. MessageBox Object (2 of 2) <ul><li>TextMessage string </li></ul><ul><ul><li>String literal or variable that displays message </li></ul></ul><ul><li>Title Bar text </li></ul><ul><ul><li>String that appears in title bar of message box </li></ul></ul><ul><li>MessageBox Buttons </li></ul><ul><ul><li>OK, OKCancel, RetryCancel, YesNo, YesNoCancel, AbortRetryIgnore </li></ul></ul><ul><li>MessageBox Icons </li></ul><ul><ul><li>Asterisk, Error, Exclamation, Hand, Information, None, Question, Stop, Warning </li></ul></ul>
    43. 43. Using Overloaded Methods <ul><li>This OOP feature allows the Show method to act differently for different arguments </li></ul><ul><li>Each argument list if called a signature so the Show method has several signatures </li></ul><ul><li>Supplied arguments must exactly match one of the signatures provided by the method </li></ul><ul><li>IntelliSense in Visual Studio editor helps when entering arguments so that they don’t need to be memorized </li></ul>
    44. 44. Testing Multiple Fields <ul><li>Each input field presents an opportunity for an exception </li></ul><ul><li>To indicate specific field that caused the exception use nested Try/Catch blocks </li></ul><ul><li>Pinpoints specific errors and after error set focus back to field in error </li></ul><ul><ul><li>Use SelectAll method of text box to make text appear selected to aid user </li></ul></ul>
    45. 45. Counting and Accumulating Sums <ul><li>Declare module-level variables, since local level variables reset to 0 each time the procedure is called </li></ul><ul><li>Summing Numbers </li></ul><ul><li>Counting </li></ul><ul><li>Calculating an Average </li></ul>discountedPriceSumDecimal += discountedPriceDecimal <ul><ul><li>Private saleCountInteger As Integer </li></ul></ul><ul><ul><li>saleCountInteger += 1 </li></ul></ul><ul><ul><li>averageDiscountedSaleDecimal = discountedPriceSumDecimal / saleCountInteger </li></ul></ul>

    ×