chapter 3 variables, constants, and calculations programming in c#.net © 2003 by the mcgraw-hill...

63
Chapter 3 Variables, Constants, and Calculations Programming in C# .NET © 2003 by The McGraw-Hill Companies, Inc. All rights reserved.

Upload: julianna-tamsin-elliott

Post on 26-Dec-2015

217 views

Category:

Documents


2 download

TRANSCRIPT

Chapter 3Variables,

Constants, and Calculations

Programming in C# .NET

© 2003 by The McGraw-Hill Companies, Inc. All rights reserved.

© 2003 by The McGraw-Hill Companies, Inc. All rights reserved.3- 2

Objectives

• Distinguish between variables, constants, and controls

• Differentiate among the various data types• Apply naming conventions incorporating

standards and indicating scope and data type• Declare variables and constants• Select the appropriate scope for a variable• Convert text input to numeric values

© 2003 by The McGraw-Hill Companies, Inc. All rights reserved.3- 3

Objectives cont.

• Perform calculations using variables and constants• Round decimal values using the decimal.Round

method• Format values for output using the ToString method• Use try/catch blocks or error handling• Display message boxes with error messages• Accumulate sums and generate counts

© 2003 by The McGraw-Hill Companies, Inc. All rights reserved.3- 4

Data – Variables and Constants

• C# allows you to set up locations in memory and give each location a name

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

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

© 2003 by The McGraw-Hill Companies, Inc. All rights reserved.3- 5

Data – Variables and Constants cont.

• Variables and named constants are given a name, called an identifier

• Declaration statements are used to create variables and constants, give them names and specify their data type

• Examples:string strName; //Declare a string variableint intCounter; //Declare an integer variableconst float fltDISCOUNT_RATE = 0.15f;

//Declare a named constant

© 2003 by The McGraw-Hill Companies, Inc. All rights reserved.3- 6

Data Types

• The data type indicates what type of information will be stored for a variable or constant

• Most common types used are string, int, and decimal

• If data will be used in a calculation, it must be numeric

• If data not used in a calculation, it will be a string• Use decimal for any decimal fractions

© 2003 by The McGraw-Hill Companies, Inc. All rights reserved.3- 7

C# Data Types

• bool

• byte

• char

• DateTime

• decimal

• float

• double

• short

• int

• long

• string

• object

© 2003 by The McGraw-Hill Companies, Inc. All rights reserved.3- 8

Identifier Naming Rules

• Identifiers created in C# must follow these rules:– May consist of letters, digits, and underscores – Must begin with a letter or underscore– Cannot contain any spaces or periods– May not be reserved words

• Names in C# are case sensitive

© 2003 by The McGraw-Hill Companies, Inc. All rights reserved.3- 9

Identifier Naming Conventions

• Identifiers created in C# should follow these guidelines:– Identifiers must be meaningful– Precede each identifier with a lowercase prefix

that specifies the data type– Capitalize each word of the name (following

the prefix); Always use mixed case for variables and uppercase for constants

© 2003 by The McGraw-Hill Companies, Inc. All rights reserved.3- 10

Common Data Types and Prefixes

Prefix Data Type Descriptionbln bool boolean

dat DateTime date and time

dec decimal decimal

dbl double double-precision floating point

int int integer

lng long long integer

flt float single-precision floating point

str string string

© 2003 by The McGraw-Hill Companies, Inc. All rights reserved.3- 11

Constants – Named and Intrinsic

• Intrinsic constants – Constants built into the Visual Studio .NET environment

• Named constants – Constants you define for yourself in the program

© 2003 by The McGraw-Hill Companies, Inc. All rights reserved.3- 12

Named Constants

• Declare named constants using keyword const• Give each constant a name, a data type, and a

value• Value of a constant cannot be changed during

execution of the project• Named constants make code easier to read• Later changes to the value of a constant are

made in only one place in code

© 2003 by The McGraw-Hill Companies, Inc. All rights reserved.3- 13

Named Constants cont.

• General formconst Datatype Identifier = Value;

• Use all uppercase for name of constant with words separated by underscores

• Examples:const string strCOMPANY_ADDRESS = “101 S. Main Street”;

const decimal decSALES_TAX_RATE = .08M;

© 2003 by The McGraw-Hill Companies, Inc. All rights reserved.3- 14

Assigning Values to Constants

• Rules for assigning values to constants– Test (string) values must be in quotation marks– Numeric values are not in quotation marks– Numeric values contain only digits (0-9), a

decimal point, and a sign (+ or -) at the left side– Numeric values cannot include a comma, dollar

sign, any special characters, or a sign at the right side

© 2003 by The McGraw-Hill Companies, Inc. All rights reserved.3- 15

Assigning Values to Constants cont.

• Type-declaration characters are used to declare data type of numeric constants

• Type-declaration characters– decimal M or m– double D or d– int I or i– long L or l– float F or f

© 2003 by The McGraw-Hill Companies, Inc. All rights reserved.3- 16

Assigning Values to Constants cont.

• Precede a quotation mark that is part of a string with a backslash (\)

• Example: “He said, \”I like it. \””

produces this string He said, “I like it.”

• Precede a backslash that is part of a string with another backslash

• Example:string strFilePath= “C:\\MyPersonalDocuments\MyLetter”;

• String values are referred to as string literals

© 2003 by The McGraw-Hill Companies, Inc. All rights reserved.3- 17

Intrinsic Constants

• Intrinsic constants are system-defined constants

• Declared in system class libraries

• Must specify class name or group name to use an intrinsic constant

• In Color.Red, “Red” is the constant and “Color” is the class

© 2003 by The McGraw-Hill Companies, Inc. All rights reserved.3- 18

Declaring Variables

• Declare a variable by specifying the data type followed by an identifier

• General Forms:Datatype Identifier;

Datatype Identifier = LiteralOfCorrectType;

• Examples:string strCustomerName;

string strCustomerName = “None”;

© 2003 by The McGraw-Hill Companies, Inc. All rights reserved.3- 19

Declaring Variables cont.

• You can declare several variables in one statement

• Separate the variable names with commas and place a semicolon at end of statement

• Examples:

string strName, strAddress, strPhone;

int intCount = 0, intTotal = 0;

© 2003 by The McGraw-Hill Companies, Inc. All rights reserved.3- 20

Initializing Numeric Variables

• Numeric variables must be assigned a value before they can be used

• Initialize a variable when you declare itint intQuantity = 0;

• Declare variable and assign value laterint intQuantity;

intQuantity = int.Parse(quantityTextBox.Text);

• Declare and initialize with expressionint intQuantity =

int.Parse(quantityTextBox.Text);

© 2003 by The McGraw-Hill Companies, Inc. All rights reserved.3- 21

Scope and Lifetime of Variables

• Scope is the visibility of a variable• Scope levels

– Namespace– Class– Local– Block

• Scope is determined by where the variable is declared

© 2003 by The McGraw-Hill Companies, Inc. All rights reserved.3- 22

Scope and Lifetime of Variables cont.

• Lifetime of a variable is the period of time that the variable exists

• Lifetime of a local or block-level variable is one execution of a method

• Lifetime of a class-level variable is the entire time the class is loaded

© 2003 by The McGraw-Hill Companies, Inc. All rights reserved.3- 23

Local Declarations

• Any variable declared inside a method is local in scope

• A declaration can appear anywhere in the method but top of the method is preferable

• Constants can also be local, block, class or namespace level

• Constants are typically declared at the class level

© 2003 by The McGraw-Hill Companies, Inc. All rights reserved.3- 24

Class-Level Declarations

• Variables or constants declared as class-level are used anywhere in the form’s class

• Place class-level declarations at top of the class, outside of any methods

• Class-level variables initialize automatically when the class is instantiated

• Numeric variables initialize to zero, string variables to null, and boolean variables to false

© 2003 by The McGraw-Hill Companies, Inc. All rights reserved.3- 25

Locations for Coding Variables and Constantsnamespace MyProjectNamespace{

public class frmMainForm : …{

declare ModuleLevelVariablesconst NamedConstantsprivate void calculateButton_Click (…){

declare LocalVariables …

{declare BlockLevelVariables

}}

}}

© 2003 by The McGraw-Hill Companies, Inc. All rights reserved.3- 26

Coding Class, Block, and Namespace-Level Declarations

• Class-level variables must be inside a class but not inside a method

• Block-level variables and constants have a scope of a block of code

• Namespace-level variables and constants are used when a project has multiple forms and/or other classes

© 2003 by The McGraw-Hill Companies, Inc. All rights reserved.3- 27

Calculations

• In programming, calculations can be performed with variables, constants, and with the properties of certain objects

• Some character strings must be converted to a different data type before they can be used in calculations

© 2003 by The McGraw-Hill Companies, Inc. All rights reserved.3- 28

Converting Strings to a Numeric Data Type

• Use the Parse method to convert the Text property of a control to its numeric form

• Each data type has its own Parse method• Example:

intQuantity = int.Parse(quantityTextBox.Text);

• Casting is the conversion of one data type to another

• Parsing means to pick apart a value, character by character, and convert it to another format

© 2003 by The McGraw-Hill Companies, Inc. All rights reserved.3- 29

Arithmetic Operations

• C# arithmetic operations– Addition– Subtraction– Multiplication– Division– Modulus

• Modulus returns the remainder of a division operation

• Use the pow method to perform exponentiation

© 2003 by The McGraw-Hill Companies, Inc. All rights reserved.3- 30

Arithmetic Operators

Operator Operation

+ Addition

- Subtraction

* Multiplication

/ Division

% Modulus – Remainder of division

© 2003 by The McGraw-Hill Companies, Inc. All rights reserved.3- 31

Order of Operations

• The order in which operations are performed determines the result

• Order of precedence1. Any operation inside parentheses

2. Multiplication and division

3. Modulus

4. Addition and subtraction

© 2003 by The McGraw-Hill Companies, Inc. All rights reserved.3- 32

Order of Operations cont.

• Use parenthesis to change the order of evaluation

• Parenthesis can be nested inside one another• Extra parenthesis can be used for clarity• Multiple operations at same level are

performed from left to right• Example:

8 / 4 * 2 = 4

© 2003 by The McGraw-Hill Companies, Inc. All rights reserved.3- 33

Order of Operations cont.

• Order of evaluation of expressions1. All operations within parentheses. Multiple operations

within the parentheses performed according to 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 left to right.

• There are no implied operations in C#

© 2003 by The McGraw-Hill Companies, Inc. All rights reserved.3- 34

Using Calculations in Code

• You can perform calculations in assignment statements

• These assignment operators perform a calculation and assign the result in one operation

+= -= *= /= %=• Example:

decTotalSales += decSales;

is the same as

decTotalSales = decTotalSales + decSales;

© 2003 by The McGraw-Hill Companies, Inc. All rights reserved.3- 35

Increment and Decrement Operators

• Increment operator (++) adds 1 to a variable• Example: intCount++;

• Decrement operator (--) subtracts 1 from the variable

• Example: intCountDown--;

• A prefix operator is placed before the variable

• A postfix operator is placed after the variable

© 2003 by The McGraw-Hill Companies, Inc. All rights reserved.3- 36

Converting between Numeric Data Types• Conversion from a narrower data type to a

wider data type is implicit conversion• Example: double dblBigNumber = intNumber;

From To

byte short, int, long, float, double, or decimal

short int, long, float, double, or decimal

int long, float, double, or decimal

long float, double, or decimal

float double

© 2003 by The McGraw-Hill Companies, Inc. All rights reserved.3- 37

Converting between Numeric Data Types cont.

• Explicit conversion also known as casting• Exception is generated if significant digits

are lost when a cast is performed• To cast, specify destination data type in

parenthesis before value to convert• Examples:

decNumber = (decimal) fltNumber;

intValue = (int) dblValue;

© 2003 by The McGraw-Hill Companies, Inc. All rights reserved.3- 38

Calculations with Unlike Data Types

• C# performs calculation with the wider data type if data types are unlike

• Example:

intCount / 2 * decAmount

1. intCount / 2 is integer division producing an integer result

2. Multiplication performed with the integer result and decimal value (decAmount) producing a decimal result

© 2003 by The McGraw-Hill Companies, Inc. All rights reserved.3- 39

Rounding Numbers

• Use the decimal.Round method to round decimal values to the desired number of decimal positions

• General formDecimal.Round(DecimalValue, IntegerNumberOfDecimalPositions)

• Example:decResult = decimal.Round(decAmount, 2);

• decimal.Round uses “rounding toward even”

© 2003 by The McGraw-Hill Companies, Inc. All rights reserved.3- 40

Formatting Data for Display

• Numeric data displayed in Text property must be converted to a string

• Can format data for display• Use ToString method and formatting codes• Use ToString with empty argument list to

return an unformatted string• Example:

displayLabel.Text = intNumber.ToString();

© 2003 by The McGraw-Hill Companies, Inc. All rights reserved.3- 41

Using Format Specifier Codes

• Use format specifier codes with ToString to format output display

• “C” code specifies currency• Example:

extendedPriceLabel.Text = (intQuantity * decPrice).ToString(“C”);

• “N” code specifies number• Example:

discountLabel.Text = decDiscount.ToString(“N”);

• Specify number of decimal positions with a digit following the code

© 2003 by The McGraw-Hill Companies, Inc. All rights reserved.3- 42

Using Format Specifier Codes cont.

• Formatted value returned by ToString method is not purely numeric and cannot be used in calculations

• Format DateTime values using format codes and the ToString method

• Date codes are case sensitive unlike numeric format codes

© 2003 by The McGraw-Hill Companies, Inc. All rights reserved.3- 43

Format Specifier Codes

Format Specifier Code

Name Description

C or c Currency Formats with dollar sign, commas, and 2 decimal places. Negative values are in parentheses.

F or f Fixed-point Formats as string of numeric digits, no commas, 2 decimal places, and minus sign at left if negative.

N or n Number Formats with commas, 2 decimal places, and a minus sign at the left for negative values.

D or d Digits Use only for integer data types. Minus sign at left for negative values. Forces number of digits to display.

P or p Percent Multiples value by 100, adds space and percent sign, rounds to 2 decimals; minus sign at left if negative.

© 2003 by The McGraw-Hill Companies, Inc. All rights reserved.3- 44

A Calculation Programming Example

R ‘n R – For Reading ‘n Refreshment – needs to calculate prices and discounts for books sold. The company is currently having a big sale, offering a 15 percent discount on all books. In this project, you will calculate the amount due for a quantity of books, determine the 15 percent discount, and deduct the discount, giving the new amount due – the discounted amount.

© 2003 by The McGraw-Hill Companies, Inc. All rights reserved.3- 45

Handling Exceptions

• Processing with invalid input or failed methods can cause an exception to occur (also called throwing an exception)

• “Catching” exceptions before they cause a run time error is called error trapping

• Coding to take care of problems is called error handling

© 2003 by The McGraw-Hill Companies, Inc. All rights reserved.3- 46

try / catch Blocks

• Enclose statement(s) that might cause an error in a try / catch block

• If an exception occurs in try block, program control transfers to the catch block

• Code in a finally statement is executed last

• Specify type of exception to catch and program several catch statements

© 2003 by The McGraw-Hill Companies, Inc. All rights reserved.3- 47

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}}}]

© 2003 by The McGraw-Hill Companies, Inc. All rights reserved.3- 48

The Exception Class

• Each exception is an instance of the Exception class

• Properties of the Exception class– Message property – Contains a text message

about the error– Source property – Contains the name of the

object causing the error– StackTrace property – Identifies the location in

the code where the error occurred

© 2003 by The McGraw-Hill Companies, Inc. All rights reserved.3- 49

Handling Multiple Exceptions

• Include multiple catch blocks (handlers) to trap for more than one exception

• Catch statements are checked in sequence• The last catch can be coded to handle any

exceptions not previously caught• A compiler warning is generated if a

variable is declared but not used in a catch block

© 2003 by The McGraw-Hill Companies, Inc. All rights reserved.3- 50

Displaying Messages in Message Boxes

• Use Show method of the MessageBox object

• Show method arguments must match one of the following formats

MessageBox.Show(TextMessage);

MessageBox.Show(TextMessage, TitlebarText);

MessageBox.Show(TextMessage, TitlebarText, MessageBoxButtons);

MessageBox.Show(TextMessage, TitlebarText, MessageBoxButtons, MessageBoxIcon);

© 2003 by The McGraw-Hill Companies, Inc. All rights reserved.3- 51

Displaying Messages in Message Boxes cont.

• TextMessage – Message to appear in the message box

– May be a string literal in quotes or a string variable

• TitleBarText – Appears on the title bar of the MessageBox window

• MessageBoxButtons – Specifies the buttons to display

– Choices are OK, OKCancel, RetryCancel, YesNo, YesNoCancel, and AbortRetryIgnore

© 2003 by The McGraw-Hill Companies, Inc. All rights reserved.3- 52

Displaying Messages in Message Boxes cont.• MessageBoxIcon

– Determines the icon to display– Constants for MessageBoxIcon

• Asterisk• Error• Exclamation• Hand• Information• None• Question• Stop• Warning

© 2003 by The McGraw-Hill Companies, Inc. All rights reserved.3- 53

MessageBox Statement ExamplesMessageBox.Show(“Enter numeric data.”);MessageBox.Show(“Try again.”, “Data Entry Error”);MessageBox.Show(“This is a message.”, “This is a title bar”,

MessageBoxButtons.OK);

try{

intQuantity = int.Parse(quantityTextBox.Text);quantityLabel.Text = intQuantity.ToString();

}catch{

MesageBox.Show(“Nonnumeric Data.”, “Error”, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);

}

© 2003 by The McGraw-Hill Companies, Inc. All rights reserved.3- 54

Using Overloaded Methods

• Overloading allows a method to act differently for different arguments

• Each argument list is called a signature

• Visual Studio .NET editor IntelliSense popup helps you enter the arguments correctly

© 2003 by The McGraw-Hill Companies, Inc. All rights reserved.3- 55

Testing Multiple Fields

• A nested try/catch block is one try/catch block completely contained inside another

• Nest the try/catch blocks as deeply as needed

• Place calculations within the most deeply nested try

© 2003 by The McGraw-Hill Companies, Inc. All rights reserved.3- 56

Counting and Accumulating Sums

• Summing numbers– Declare variable as class level to hold the total– Example: decPriceSum += decPrice;

• Counting– Declare variable as class level integer to hold count– Example: intSaleCount ++;

• Calculating an average– Divide the sum of numbers by the count

– Example: decAverageSale = decPriceSum / intSaleCount;

© 2003 by The McGraw-Hill Companies, Inc. All rights reserved.3- 57

Your Hands-On Programming Example

In this project, R ‘n R – For Reading ‘n Refreshment needs to expand its book sale project done previously in this chapter. In addition to calculating individual sales and discounts, management wants to know the total number of books sold, the total number of discounts given, the total discounted amount, and the average discount per sale.

© 2003 by The McGraw-Hill Companies, Inc. All rights reserved.3- 58

Your Hands-On Programming Example cont.

Help the user by adding ToolTips wherever you think them useful.

Add error handling to the program so that missing or nonnumeric data will not cause a run-time error.

© 2003 by The McGraw-Hill Companies, Inc. All rights reserved.3- 59

Summary

• Variables are temporary memory locations that have a name, data type, and scope. Constants also have a name, data type, scope, and value assigned that cannot change.

• Data type determines the type of values that can be assigned to a variable or constant.

• Identifiers for variables and constants must follow C# naming rules and should following conventions.

• Intrinsic constants are predefined and built into the .NET Framework. Named constants are programmer-defined.

© 2003 by The McGraw-Hill Companies, Inc. All rights reserved.3- 60

Summary cont.

• Variables are declared by indicating the data type and identifier. Location of declaration determines the scope.

• The scope of a variable may be namespace level, class level, local or block level.

• The lifetime of a local and block-level variables is one execution of the methods where they were declared. The lifetime of a class-level variable is the length of time the class is loaded.

© 2003 by The McGraw-Hill Companies, Inc. All rights reserved.3- 61

Summary cont.

• Identifiers should include a prefix defining the data type of the variable or constant.

• Use the Parse methods to convert text values to numeric before performing calculations.

• Calculations are performed using numeric variables, constants, and properties of controls. Result is assigned to a numeric variable or the property of a control.

• Calculations with more than one operator follow the order of precedence. Parentheses may alter the order of operations.

© 2003 by The McGraw-Hill Companies, Inc. All rights reserved.3- 62

Summary cont.

• The decimal.Round method rounds a decimal value to the specified number of decimal positions.

• The ToString method is used to specify the appearance of values for display.

• try/catch/finally statements used to check for user errors

• An error is called an exception. Catching and taking care of exceptions is error trapping and error handling.

© 2003 by The McGraw-Hill Companies, Inc. All rights reserved.3- 63

Summary cont.

• Trap for different types of errors by specifying the exception type on the catch statement.

• A message box is used to display information to the user.

• The Show method of the MessageBox class is overloaded.

• Calculate sums and counts by adding class-level variables for calculations.