McGraw-Hill © 2010 The McGraw-Hill Companies, Inc. All rights reserved. Chapter 3 Variables, Constants and Calculations.

Slides:



Advertisements
Similar presentations
Lecture Set 4 Data Types and Variables Part B – Variables, Constants, Expressions Conversion Rules Options Strict, Option Explicit Scope of Definition.
Advertisements

Chapter 3 Variables, Constants, and Calculations Copyright © 2011 by The McGraw-Hill Companies, Inc. All Rights Reserved. McGraw-Hill.
1 Chapter 2 Introduction to Java Applications Introduction Java application programming Display ____________________ Obtain information from the.
Introduction to C Programming
Variables, Constants, and Calculations. Data — Variables and Constants (1 of 2) Variable  Memory locations that hold data that can be changed during.
Chapter 3 Variables, Constants, and Calculations
1 Chapter 4 Language Fundamentals. 2 Identifiers Program parts such as packages, classes, and class members have names, which are formally known as identifiers.
CMT Programming Software Applications
 2007 Pearson Education, Inc. All rights reserved Introduction to C Programming.
Data types and variables
Chapter 2 Data Types, Declarations, and Displays
JavaScript, Third Edition
Introduction to C Programming
CSci 142 Data and Expressions. 2  Topics  Strings  Primitive data types  Using variables and constants  Expressions and operator precedence  Data.
Basic Elements of C++ Chapter 2.
Chapter 3 Variables, Constants, and Calculations Copyright © 2011 by The McGraw-Hill Companies, Inc. All Rights Reserved. McGraw-Hill.
1 Chapter Two Using Data. 2 Objectives Learn about variable types and how to declare variables Learn how to display variable values Learn about the integral.
Objectives You should be able to describe: Data Types
Chapter 3 Variables, Constants, and Calculations Programming in C#.NET © 2003 by The McGraw-Hill Companies, Inc. All rights reserved.
McGraw-Hill © 2009 The McGraw-Hill Companies, Inc. All rights reserved. Chapter 3 Variables, Constants, and Calculations.
McGraw-Hill © 2009 The McGraw-Hill Companies, Inc. All rights reserved. Chapter 3 Variables, Constants, and Calculations.
Variables, Constants, and Calculations
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 2 Input, Processing, and Output.
© 2002 The McGraw-Hill Companies, Inc. All rights reserved. 1 McGraw-Hill/Irwin Programming with Java Chapter 4 Performing Calculations and Formatting.
Variables, Constants, and Calculations
3-1 aslkjdhfalskhjfgalsdkfhalskdhjfglaskdhjflaskdhjfglaksjdhflakshflaksdhjfglaksjhflaksjhf.
Introduction to Visual Basic. Introduction In this chapter, we introduce Visual Basic programming with program code. We demonstrate how to display information.
Arithmetic operations and operators, converting data types and formatting programs for output. Year 11 Information Technology.
Chapter 3 Processing and Interactive Input. 2 Assignment  The general syntax for an assignment statement is variable = operand; The operand to the right.
Introduction to Java Applications Part II. In this chapter you will learn:  Different data types( Primitive data types).  How to declare variables?
CH2 – Using Data. Constant Something which cannot be changed Data Type Format and size of a data item Intrinsic Data Types Pg. 47 – Table 2-1 Basic ones.
Input, Output, and Processing
Chapter 2: Using Data.
Microsoft Visual Basic 2005 CHAPTER 4 Variables and Arithmetic Operations.
Variables, Constants, and Calculations. Calculations Although the calculations themselves are quite simple (addition, subtraction, multiplication, and.
Microsoft Visual Basic 2005: Reloaded Second Edition Chapter 3 Variables, Constants, Methods, and Calculations.
CHAPTER 4 GC 101 Data types. DATA TYPES  For all data, assign a name (identifier) and a data type  Data type tells compiler:  How much memory to allocate.
Copyright Curt Hill Variables What are they? Why do we need them?
Chapter 3 Variables, Constants and Calculations Programming In Visual Basic.NET.
Chapter 2 Variables.
Microsoft Visual Basic 2010: Reloaded Fourth Edition Chapter Three Memory Locations and Calculations.
Variables and Constants Variable Memory locations that hold data that can be changed during project execution Example: a customer’s name Constant Memory.
A Simple Java Program //This program prints Welcome to Java! public class Welcome { public static void main(String[] args) { public static void main(String[]
Exceptions, handling exceptions & message boxes Year 11 Information Technology.
 2008 Pearson Education, Inc. All rights reserved JavaScript: Introduction to Scripting.
Operators and Expressions. 2 String Concatenation  The plus operator (+) is also used for arithmetic addition  The function that the + operator performs.
1 Chapter 3 – Examples The examples from chapter 3, combining the data types, variables, expressions, assignments, functions and methods with Windows controls.
3-1 aslkjdhfalskhjfgalsdkfhalskdhjfglaskdhjflaskdhjfglaksjdhflakshflaksdhjfglaksjhflaksjhf.
Programming with Microsoft Visual Basic th Edition
 2001 Prentice Hall, Inc. All rights reserved. 1 Chapter 3 – Introduction to C# Programming Outline 3.1 Introduction 3.2 Simple Program: Printing a Line.
Introduction to Java Applications Part II. In this chapter you will learn:  Different data types( Primitive data types).  How to declare variables?
110 E-1 Variables, Constants and Calculations(2) Chapter 3: Operations on variables, scope of a variable, formatting data Doing Arithmetic.
Microsoft Visual Basic 2012 CHAPTER FOUR Variables and Arithmetic Operations.
Chapter 4.  Variables – named memory location that stores a value.  Variables allows the use of meaningful names which makes the code easier to read.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 2-1 Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley.
Microsoft Visual Basic 2010 CHAPTER FOUR Variables and Arithmetic Operations.
A variable is a name for a value stored in memory.
Chapter 2 Variables.
Chapter 3: Variables, Constants, and Calculations
Arithmetic operations and operators, converting data types and formatting programs for output. Year 11 Information Technology.
Variables and Arithmetic Operations
Lecture Set 4 Data Types and Variables
Variables and Arithmetic Operations
CIS16 Application Development Programming with Visual Basic
Chapter 2 Variables.
Brief description on how to navigate within this presentation (ppt)
Introduction to Visual Basic
Introduction to Java Applications
Chapter 2 Variables.
Brief description on how to navigate within this presentation (ppt)
Presentation transcript:

McGraw-Hill © 2010 The McGraw-Hill Companies, Inc. All rights reserved. Chapter 3 Variables, Constants and Calculations

McGraw-Hill© 2010 The McGraw-Hill Companies, Inc. All rights reserved. 3-2 Chapter Objectives - 1 Distinguish between variables, constants, and controls Differentiate among the various data types Apply naming conventions incorporating standards and indicating the data type Declare variables and constants Select the appropriate scope for a variable Convert text input to numeric values

McGraw-Hill© 2010 The McGraw-Hill Companies, Inc. All rights reserved. 3-3 Chapter Objectives - 2 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

McGraw-Hill© 2010 The McGraw-Hill Companies, Inc. All rights reserved. 3-4 Data – Variables and Constants - 1 Variable –Memory locations that hold data that can change during project execution Example: Customer's name Constant –Memory locations that hold data that cannot change during execution Examples: Company name or sales tax rate

McGraw-Hill© 2010 The McGraw-Hill Companies, Inc. All rights reserved. 3-5 Data – Variables and Constants - 2 Declare a variable or named constant –C# reserves an area of memory –Assign a name, called an identifier –Specify identifier names according to C# rules and naming conventions Declaration statements –Establish project variables and constants –Give variables and constants names –Specify type of data held –Not executable

McGraw-Hill© 2010 The McGraw-Hill Companies, Inc. All rights reserved. 3-6 Data – Variables and Constants - 3 Sample declaration statements //Declare a string variable. string nameString; //Declare integer variables. int counterInteger; int maxInteger = 100; //Declare a named constant. const decimal DISCOUNT_RATE_Decimal =.15M;

McGraw-Hill© 2010 The McGraw-Hill Companies, Inc. All rights reserved. 3-7 Data Types - 1 booltrue or false values byte0 to 255, binary data charSingle Unicode character DateTime1/1/ :00:00 through 12/31/ :59:59 decimalDecimal fractions, such as dollars & cents, precision of 28 digits floatSingle-precision floating-point numbers, six digits of accuracy doubleDouble-precision floating-point numbers, 14 digits of accuracy shortSmall integer in the range –32,768 to +32,767 intWhole numbers in the range – 2,147,483,648 to +2,147,483,647 longLarger whole numbers stringAlphanumeric data: letters, digits and other characters objectAny type of data

McGraw-Hill© 2010 The McGraw-Hill Companies, Inc. All rights reserved. 3-8 Data Types - 2 Common types of variables and constants –string –int –decimal Guideline for use –Data used in calculations must be numeric decimal – any decimal fraction including dollars int – whole number calculations float and double – scientific applications –Text characters and numbers not used in calculations string – including phone or social security numbers

McGraw-Hill© 2010 The McGraw-Hill Companies, Inc. All rights reserved. 3-9 Naming Rules May contain letters, digits, and underscores Must begin with a letter or underscore Cannot contain spaces or periods Cannot be reserved words (keywords) –Examples: print, name, value Case sensitive –sumInteger, SumInteger, suminteger and SUMINTEGER are different variables

McGraw-Hill© 2010 The McGraw-Hill Companies, Inc. All rights reserved Naming Conventions Should follow naming conventions –Identifiers must be meaningful Clearly indicate the purpose Do not abbreviate Do not use X or Y –Include the class (data type) –Use camel casing for variables Begin with a lowercase letter Capitalize each successive word –Use uppercase for constants Separate words with underscores

McGraw-Hill© 2010 The McGraw-Hill Companies, Inc. All rights reserved Constants: Named and Intrinsic Constants contain a value that does not change Intrinsic –Built into the environment, not defined Named –Defined by programmer

McGraw-Hill© 2010 The McGraw-Hill Companies, Inc. All rights reserved Named Constants - 1 Declare using keyword const Assign name, data type, value A constant’s value cannot be changed during a project’s execution Data type declared and data type of value must match –Example – integer constant declared, integer value must be assigned

McGraw-Hill© 2010 The McGraw-Hill Companies, Inc. All rights reserved Named Constants - 2 Two advantages to using –Easier to read MAXIMUM_PAY_Decimal more meaningful than 1000 To change value, change constant declaration once, not every reference in code const Statement – Examples const string COMPANY_ADDRESS_String = “101 S. Main Street”; const decimal SALES_TAX_RATE_Decimal =.08m;

McGraw-Hill© 2010 The McGraw-Hill Companies, Inc. All rights reserved Assigning Values to Constants - 1 Numeric constants –May contain only digits (0-9) –Decimal point –Sign at the left side (+ or -) –Type declaration character at the right side (optional) –Cannot contain comma, dollar sign, any other special characters, sign (+ or -) at right side –Use type declaration character to specify the data type Without type declaration character, whole numbers assumed to be int and fractional values assumed to be double decimalM or m doubleD or d longL or l shortS or s floatF or f

McGraw-Hill© 2010 The McGraw-Hill Companies, Inc. All rights reserved Assigning Values to Constants - 2 String constants (or literals) –Enclose in quotes –Can contain letters, digits, and special characters –To include a quotation mark within a literal, precede the quotation mark with a backslash (\) "He said, \“I like it.\" " produces the string: He said, “I like it."

McGraw-Hill© 2010 The McGraw-Hill Companies, Inc. All rights reserved Intrinsic Constants System-defined constants Declared in system class libraries Specify class name or group name and constant name –Example – Color.Red is the constant “Red” in the class “Color”

McGraw-Hill© 2010 The McGraw-Hill Companies, Inc. All rights reserved Declaring Variables - 1 Declare a variable –Specify data type and follow with an identifier –Assign an initial value (optional) string customerNameString; string customerNameString = “None”; private int totalSoldInteger; int totalSoldInteger = 0; float temperatureFloat; float temperatureFloat = 32f; decimal priceDecimal; private decimal priceDecimal = 99.95m;

McGraw-Hill© 2010 The McGraw-Hill Companies, Inc. All rights reserved Declaring Variables - 2 Declare several variables in one statement –Data type at beginning of statement applies to all variables in statement –Separate variable names with commas –End statement with a semicolon (;) string nameString, addressString, phoneString; decimal priceDecimal, totalDecimal; int countInteger = 0, totalInteger = 0;

McGraw-Hill© 2010 The McGraw-Hill Companies, Inc. All rights reserved Initializing Numeric Variables Must assign a value before use –Variable must appear on left side of equal sign before used on right side of equal sign Initialize a variable when declared int quantityInteger = 0; Or declare variable and assign value later int quantityInteger; quantityInteger = int.Parse(quantityTextBox.Text);

McGraw-Hill© 2010 The McGraw-Hill Companies, Inc. All rights reserved Entering Declaration Statements IntelliSense helps in entering declaration statements –Type correct entry –List scrolls to correct section –When correct entry is highlighted Press Enter, Tab, or spacebar or double-click entry with mouse

McGraw-Hill© 2010 The McGraw-Hill Companies, Inc. All rights reserved Scope and Lifetime of Variables Visibility of a variable is its scope –Namespace Also referred to as global –Class-level –Local –Block Scope of variable determined by where it is declared

McGraw-Hill© 2010 The McGraw-Hill Companies, Inc. All rights reserved Variable Lifetime Period of time a variable exists –Local or block variable One execution of a method After execution variables disappear, memory locations are released –Class-level variable Entire time class is loaded (usually lifetime of project) Variables maintain value for multiple executions of a method

McGraw-Hill© 2010 The McGraw-Hill Companies, Inc. All rights reserved Local Declarations Variable declared inside a method is local in scope –Known only to that method Must be declared prior to first use –All declarations should appear at the top of a method (after comments) All constants should be declared at class level –Easy to locate to facilitate any changes

McGraw-Hill© 2010 The McGraw-Hill Companies, Inc. All rights reserved Class-Level Declarations Variables declared at class level can be used anywhere in that form’s class Place after opening brace for class, outside of any method Class variables and constants

McGraw-Hill© 2010 The McGraw-Hill Companies, Inc. All rights reserved Calculations Calculations are performed with –Variables –Constants –Properties of certain objects i.e. Text property of text box or label Character strings must be converted to correct data type first

McGraw-Hill© 2010 The McGraw-Hill Companies, Inc. All rights reserved Converting Strings to a Numeric Data Type Parse method converts the Text property of a control to a numeric value that can be used in calculations int.Parse converts text to an integer decimal.Parse converts text to a decimal Pass the text string to convert as an argument of the Parse method // Convert input values to numeric variables. quantityInteger = int.Parse(quantityTextBox.Text); priceDecimal = decimal.Parse(priceTextBox.Text); //Calculate the extended price. extendedPriceDecimal = quantityInteger * priceDecimal;

McGraw-Hill© 2010 The McGraw-Hill Companies, Inc. All rights reserved Using the Parse Methods Parse attempts to convert the string to the specified data type –Values such as blanks or nonnumeric characters cause an error Parse methods exist for long, float or double conversions quantityInteger = int.Parse(quantityTextBox.Text); priceDecimal = decimal.Parse(priceTextBox.Text); wholeNumberInteger = int.Parse(digitString);

McGraw-Hill© 2010 The McGraw-Hill Companies, Inc. All rights reserved Converting to String Assignment must be of like types –Assign a string value to a string variable or property –Assign a numeric value to a numeric variable or property To assign the result of a calculation to the Text property of a control, use the ToString method resultTextBox.Text = resultDecimal.ToString(); countTextBox.Text = countInteger.ToString(); idString = idInteger.ToString();

McGraw-Hill© 2010 The McGraw-Hill Companies, Inc. All rights reserved Arithmetic Operations - 1 OperatorOperation +Addition –Subtraction  Multiplication /Division %Modulus – remainder of division

McGraw-Hill© 2010 The McGraw-Hill Companies, Inc. All rights reserved Arithmetic Operations - 2 Modulus (%) –Returns the remainder of a division operation // Assume that totalMinutesInteger = 150 minutesInteger = totalMinutesInteger % 60; // Result is 30. // (150 divided by 60 is 2 with a remainder of 30.)

McGraw-Hill© 2010 The McGraw-Hill Companies, Inc. All rights reserved Arithmetic Operations - 3 Division (/) –Divide fractional values or integers –If at least one value is fractional, the result is fractional –If both values are integer, the result is integer (any remainder is dropped) // Assume that minutesInteger = 150 // Integer division. hoursInteger = minutesInteger / 60; // Result is 2. // Fractional division. hoursFloat = minutesInteger / 60.0f; // Result is 2.5.

McGraw-Hill© 2010 The McGraw-Hill Companies, Inc. All rights reserved Arithmetic Operations - 4 Exponentiation –C# does not have an operator for exponentiation –Use Math.Pow See Appendix B for Math methods See Chapter 5 for an example –“Writing a Method with Multiple Arguments”

McGraw-Hill© 2010 The McGraw-Hill Companies, Inc. All rights reserved Order of Operations - 1 Hierarchy of operations or order of precedence in arithmetic expressions 1. Any operation inside parentheses 2. Multiplication and division 3. Modulus 4. Addition and subtraction

McGraw-Hill© 2010 The McGraw-Hill Companies, Inc. All rights reserved Order of Operations - 2 Using parentheses controls the order of evaluation  2 = 11Multiply then add (3 + 4)  2 = 14Add then multiply 8 / 4  2 = 4Divide then multiply 8 / (4  2) = 1Multiply then divide

McGraw-Hill© 2010 The McGraw-Hill Companies, Inc. All rights reserved Order of Operations - 3 Evaluation of an expression occurs in this order 1.All operations within parentheses Multiple operations within the parentheses are performed according to the rules of precedence 2.All multiplication and division Multiple operations are performed from left to right 3.Modulus operations Multiple operations are performed from left to right 4.All addition and subtraction are performed from left to right

McGraw-Hill© 2010 The McGraw-Hill Companies, Inc. All rights reserved Using Calculations in Code Perform calculations in assignment statements –Calculation appears on the right side of the equal sign –Result is assigned to a variable or property on the left side of the equal sign (never a constant) averageDecimal = sumDecimal / countInteger; amountDueLabel.Text = (priceDecimal – (priceDecimal * discountRateDecimal)).ToString(); commissionTextBox.Text = (salesTotalDecimal * commissionRateDecimal).ToString();

McGraw-Hill© 2010 The McGraw-Hill Companies, Inc. All rights reserved Assignment Operators Combined assignment operators –Perform both a calculation and an assignment += Add to the operator on the left totalSalesDecimal += saleDecimal; –= Subtract from the operator on the left countDownInteger –= 1;  = Multiply by operator on left and assign result to the operator resultInteger  = 2; /= Divide into operator on left and assign result to the operator sumDecimal /= countInteger; += (Strings) concatenate to the operator on the left bigString += smallString;

McGraw-Hill© 2010 The McGraw-Hill Companies, Inc. All rights reserved Increment and Decrement Operators Increment ( ++ ) — Adds 1 to a variable countInteger++; Decrement (– –) — Subtracts 1 from the variable countDownInteger– –; Prefix notation –Prefix to perform the increment before the arithmetic operation Add 1 to countInteger before subtracting from 100 resultInteger = 100 – ++countInteger; Postfix notation –Postfix to perform the increment after the arithmetic operation Subtract countInteger from 100 before incrementing countInteger resultInteger = 100 – countInteger++;

McGraw-Hill© 2010 The McGraw-Hill Companies, Inc. All rights reserved Converting between Numeric Data Types - 1 Implicit conversions –Converts value from narrower data type to a wider type when there is no danger of losing precision Note: C# has no implicit conversions to convert from decimal FromTo byteshort, int, long, float, double, decimal shortint, long, float, double, decimal intlong, float, double, decimal longfloat, double, decimal floatdouble

McGraw-Hill© 2010 The McGraw-Hill Companies, Inc. All rights reserved Converting between Numeric Data Types - 2 Explicit conversions –Also called casting –Convert between data types without implicit conversions –Specify the destination data type in parentheses before the data value to convert –Generates an exception if significant digits will be lost numberDecimal = (decimal) numberFloat; valueInt = (int) valueDouble;

McGraw-Hill© 2010 The McGraw-Hill Companies, Inc. All rights reserved Converting between Numeric Data Types - 3 Convert class methods –C# methods available ToDecimal, ToSingle, ToDouble –Integer data types use.NET class names short – ToInt16 int – ToInt32 long – ToInt64 –Examples numberDecimal = Convert.ToDecimal(numberSingle); valueInteger = Convert.ToInt32(valueDouble);

McGraw-Hill© 2010 The McGraw-Hill Companies, Inc. All rights reserved Performing Calculations with Unlike Data Types C# performs the calculations using the wider data type Perform a cast if you want to convert the result to a different data type (int) countInteger / numberDecimal (float) countInteger / numberDecimal C# does not convert to a different data type until necessary countInteger / 2  amountDecimal –Division produces an integer intermediate result; then multiplication produces a decimal result

McGraw-Hill© 2010 The McGraw-Hill Companies, Inc. All rights reserved Rounding Numbers Round decimal fractions using decimal.Round –Returns a decimal result rounded to the specified number of digits // Round to two decimal positions. resultDecimal = decimal.Round(amountDecimal, 2); decimal.Round and Convert methods use "rounding toward even" if the digit to the right of the final digit is exactly 5. Decimal value to round Number of decimal positions Result

McGraw-Hill© 2010 The McGraw-Hill Companies, Inc. All rights reserved Formatting Data for Display Display numeric data in a label or text box by converting the value to a string –Use ToString method displayTextBox.Text = numberInteger.ToString(); Format the data using formatting codes as an argument of the ToString method –Specifies dollar sign, percent sign, and commas –Specifies the number of digits to the right of the decimal point

McGraw-Hill© 2010 The McGraw-Hill Companies, Inc. All rights reserved Using Format Specifier Codes - 1 "C" or "c" – Currency –String formatted with a dollar sign, commas separating each group of three digits, and two digits to the right of the decimal point extendedpriceTextBox.Text = (quantityInteger * priceDecimal).ToString("C"); "N" or "n" – Number –String formatted with commas separating each group of three digits, two digits to right of the decimal point discountTextBox.Text = discountDecimal.ToString("N"); Specify number of decimal positions by placing a numeric digit following the specifier code discountTextBox.Text = discountDecimal.ToString("N3");

McGraw-Hill© 2010 The McGraw-Hill Companies, Inc. All rights reserved Using Format Specifier Codes - 2 Additional Format Specifier Codes –"F" or "f" – Fixed point String of numeric digits, no commas, two decimal places, minus sign at left for negative values –"D" or "d" – Digits Force a specified number of digits to display For integer data types only, minus sign at left –"P" or "p" – Percent Multiplies the value by 100, adds a space and a percent sign, rounds to two decimal places –Additional codes for dates and times d, D, t, T, f, F, g, G, m, M, r, R Date and time codes are case sensitive

McGraw-Hill© 2010 The McGraw-Hill Companies, Inc. All rights reserved Choosing the Controls for Program Output Output can display in labels or text boxes –Labels – Cannot be changed by the user Used traditionally for program output –Text boxes – Can be changed by the user To use for output –Set ReadOnly property to true (BackColor property changes to Control) –Set TabStop property to false –Set BorderStyle property to Fixed3D or FixedSingle Advantages over using labels for output –Text boxes do not disappear when cleared –Form layout looks more uniform –The clipboard Copy command is available to the user

McGraw-Hill© 2010 The McGraw-Hill Companies, Inc. All rights reserved Format Specifier Code Examples VariableValue Format Specifier Code Output totalDecimal "C"$1, totalDecimal "N"1, totalDecimal "N0"1,126 balanceDecimal "N3"1, balanceDecimal "F0"1126 pinInteger123"D6" rateDecimal0.075"P"7.50 % rateDecimal0.075"P3"7.500 % rateDecimal0.075"P0"8 % valueInteger–10"C"($10.00) valueInteger–10"N"– valueInteger–10"D3"– 010

McGraw-Hill© 2010 The McGraw-Hill Companies, Inc. All rights reserved Handling Exceptions Exceptions cause run-time errors –Blank or non-numeric data cause Parse methods to fail –Entering a number that results in an attempt to divide by zero Exception Handling catches bad data before a run-time error occurs –Writing code to catch exceptions is called exception handling –Exception handling in Visual Studio.NET is standardized for all languages that use the CLR

McGraw-Hill© 2010 The McGraw-Hill Companies, Inc. All rights reserved try/catch Blocks Enclose any statement(s) that might cause an error in a try/catch block –If an exception occurs while the statements in the try block are executing, program control transfers to the catch block –The code in a finally block (if included) executes last, whether or not an exception occurred

McGraw-Hill© 2010 The McGraw-Hill Companies, Inc. All rights reserved The try Block – General Form try { // Statements that may cause error. } catch [(ExceptionType [VariableName])] { // Statements for action when exception occurs. } [finally { // Statements that always execute before exit of try block. }]

McGraw-Hill© 2010 The McGraw-Hill Companies, Inc. All rights reserved The try Block - Example Write different catch statements to specify the type of exception to catch This catch will catch any exception try { quantityInteger = int.Parse(quantityTextBox.Text); quantityTextBox.Text = quantityInteger.ToString(); } catch { messageLabel.Text = "Error in input data."; }

McGraw-Hill© 2010 The McGraw-Hill Companies, Inc. All rights reserved The Exception Class - 1 Each exception is an instance of the Exception class –The properties of this class allow the programmer to: Determine the code location of the error Determine the type and cause of the error The Message property contains a text message about the error The Source property contains the name of the object causing the error

McGraw-Hill© 2010 The McGraw-Hill Companies, Inc. All rights reserved The Exception Class - 2 Include the text message associated with the exception Declare a variable name in the catch statement for the exception catch (FormatException theException) { messageLabel.Text = "Error in input data: " theException.Message; }

McGraw-Hill© 2010 The McGraw-Hill Companies, Inc. All rights reserved Handling Multiple Exceptions - 1 Include multiple catch blocks (handlers) Catch statements are checked in sequence First one with a matching exception is used Same variable name can be used for multiple catch statements –Variable’s scope is only that block –Omit variable name for exception if no need to refer to properties of the exception object in the catch block

McGraw-Hill© 2010 The McGraw-Hill Companies, Inc. All rights reserved Handling Multiple Exceptions - 2 catch (FormatException theException) { // Statements for nonnumeric data. } catch (ArithmeticException theException) { // Statements to handle calculation problem. } catch (Exception theException) { // Statements for any other exception. }

McGraw-Hill© 2010 The McGraw-Hill Companies, Inc. All rights reserved Displaying Messages in Message Boxes Display a message in a message box –User has entered invalid data –User neglects to enter required data Specify message, optional icon, title bar text and buttons Use Show method of the MessageBox object to display a message box

McGraw-Hill© 2010 The McGraw-Hill Companies, Inc. All rights reserved The MessageBox Object – General Form Arguments must match one of the formats Do not reverse, transpose or leave out any argument MessageBox.Show(TextMessage); MessageBox.Show(TextMessage, TitlebarText); MessageBox.Show(TextMessage, TitlebarText, MessageBoxButtons); MessageBox.Show(TextMessage, TitlebarText, MessageBoxButtons, MessageBoxIcon);

McGraw-Hill© 2010 The McGraw-Hill Companies, Inc. All rights reserved The TextMessage String TextMessage String –String literal enclosed in quotes –String variable –May concatenate several items i.e. Combine a literal with a variable value –If message is too long, will wrap to next line

McGraw-Hill© 2010 The McGraw-Hill Companies, Inc. All rights reserved The Titlebar Text TitlebarText –Appears in the title bar of message box –If no TitlebarText argument, title bar will appear empty

McGraw-Hill© 2010 The McGraw-Hill Companies, Inc. All rights reserved MessageBox Buttons Specify button(s) to display –Use the MessageBoxButtons constants of MessageBox class OK (default) OKCancel RetryCancel YesNo YesNoCancel AbortRetryIgnore

McGraw-Hill© 2010 The McGraw-Hill Companies, Inc. All rights reserved MessageBoxIcon IntelliSense pops up with complete list Constants for MessageBoxIcon –Asterisk –Error –Exclamation –Hand –Information –None –Question –Stop –Warning

McGraw-Hill© 2010 The McGraw-Hill Companies, Inc. All rights reserved Using Overloaded Methods Overloading allows the Show method to act differently for different arguments Each argument list is called a signature –The Show method has several signatures Supplied arguments must exactly match one of the signatures IntelliSense helps in entering the arguments (no need to look up or memorize the signatures)

McGraw-Hill© 2010 The McGraw-Hill Companies, Inc. All rights reserved Testing Multiple Fields Each input field presents an opportunity for an exception To indicate the field that caused the error, nest one try/catch block inside another one

McGraw-Hill© 2010 The McGraw-Hill Companies, Inc. All rights reserved Nested try/catch Blocks - 1 One try/catch block completely contained inside another one is a nested try/catch block –Nest as deeply as needed –Place calculations within the most deeply nested try Do not perform calculations unless all input values are converted without an exception –Test each Parse method Specify which field caused error and set focus back to field in error Use SelectAll method of text box –Makes text appear selected to aid user

McGraw-Hill© 2010 The McGraw-Hill Companies, Inc. All rights reserved Nested try/catch Blocks - 2 try // Outer try block for the first field. { // Convert first field to numeric. try // Inner try block for the second field. { // Convert second field to numeric. // Perform the calculations for the fields that passed conversion. } catch (FormatException secondException) { // Handle any exceptions for the second field. // Display a message and reset the focus for the second field. } // End of inner try block for the second field. } catch (FormatException firstException) { // Handle exceptions for the first field. // Display a message and reset the focus for the first field. }

McGraw-Hill© 2010 The McGraw-Hill Companies, Inc. All rights reserved Counting & Accumulating Sums Declare a class level variable –Retains its value for multiple calls Allows accumulation of totals Static variables –Discussed in Chapter 12

McGraw-Hill© 2010 The McGraw-Hill Companies, Inc. All rights reserved Summing Numbers Declare a class-level variable Inside the calculate event handler –Add the current amount to the total totalAmountDecimal += amountDecimal;

McGraw-Hill© 2010 The McGraw-Hill Companies, Inc. All rights reserved Counting Declare a counter variable as integer at the class-level int saleCountInteger; Add 1 to the counter variable in the calculate event method saleCountInteger ++;

McGraw-Hill© 2010 The McGraw-Hill Companies, Inc. All rights reserved Calculating an Average Divide sum of items by count of items averageSaleDecimal = totalAmountDecimal / saleCountInteger;