53
Variables, Calculations, Formatting Numbers, and Catching Errors Part 5 dbg

Variables, Calculations, Formatting Numbers, and Catching Errors Part 5 dbg

Embed Size (px)

Citation preview

Page 1: Variables, Calculations, Formatting Numbers, and Catching Errors Part 5 dbg

Variables, Calculations, Formatting Numbers, and

Catching Errors

Part 5 dbg

Page 2: Variables, Calculations, Formatting Numbers, and Catching Errors Part 5 dbg

Built-in Value Data Types

Page 3: Variables, Calculations, Formatting Numbers, and Catching Errors Part 5 dbg

3

Built-in Integer Data Types

C# keyword

DescriptionBytes

Storage.NET Class

byte positive integer between 0 and +255 1 Byte

sbyte signed integer value from -128 to +127 1 SByte

short signed integer from -32,768 to 32,767 2 Int16

ushort unsigned integer from 0 to +65,535 2 UInt16

int signed integer from -2,147.483,648 to +2,147.483,647

4 Int32

uint unsigned integer from 0 to +4,294,967,295 4 UInt32

long signed integer from -9,223,372,036,854,775,808 to +9,223,372,036,854,775,807

8 Int64

ulong unsigned integer from 0 to +18,446,744,073,709,551,615

8 UInt64

Page 4: Variables, Calculations, Formatting Numbers, and Catching Errors Part 5 dbg

4

Built-in Floating-Point Data Types

C# keyword

DescriptionBytes

Storage.NET Class

float floating point numbers (6 digits of precision) 4 Single

double floating point numbers with greater range and precision (14 digits of precision)

8 Double

decimal monetary values with accurate rounding (28 digits of precision)

16 Decimal

Page 5: Variables, Calculations, Formatting Numbers, and Catching Errors Part 5 dbg

5

Other Built-in Value Data Types

C# keyword

Description Bytes Storage

.NET Class

bool a true or false value 1 Boolean

char a single Unicode character; designate a char value with single quotes

2 Char

Page 6: Variables, Calculations, Formatting Numbers, and Catching Errors Part 5 dbg

6

Built-in Reference Data Type

C# keyword

DescriptionBytes

Storage.NET Class

string A reference to a String object (multiple letters, numbers, & punctuation); designate a string with double quotes

Varies String

object A reference to any type of object Varies Object

Page 7: Variables, Calculations, Formatting Numbers, and Catching Errors Part 5 dbg

7

Variables

• A variable is a programmer-assigned name associated with a storage/memory location; the word variable implies that the associated value may change during the program lifetime.

• A variable must be declared before it can be used.

Syntax: data-type identifier ;decimal grossPay; int age;bool latePayment; string firstName;

• Use camel casing for multi-word variable identifiers.

Page 8: Variables, Calculations, Formatting Numbers, and Catching Errors Part 5 dbg

8

Named Constants

• Use a named constant for a value that will not change during the program lifetime.

• Use of named constants adds meaning to your program and allows for a change in one location rather than throughout your code.

• Use the keyword const in front of your declaration and type the identifier in all caps.

const decimal SALES_TAX_RATE = 0.0825d;const string STATE = “NY”;

• Named constants are typically declared before other variables in your program.

Page 9: Variables, Calculations, Formatting Numbers, and Catching Errors Part 5 dbg

9

Intrinsic Constants

• Intrinsic constants are constants defined in system class libraries.

• You may use them in your program.• Color.Red, Color.Yellow, and Color.AliceBlue

are color constants declared in the Color class.

/*the following statement sets the background color of form to Alice Blue color at run time*/

frmOriginal.BackColor = Color.AliceBlue;

Page 10: Variables, Calculations, Formatting Numbers, and Catching Errors Part 5 dbg

10

Initialization of Variables

• Assigning a starting value to a variable is called initialization.

• Declaring an initial value for a variable is optional, but a variable must have a value before it is used in an assignment or calculation.

int counter = 0;

bool foundIt = false;

double otMultiplier = 1.5;

Page 11: Variables, Calculations, Formatting Numbers, and Catching Errors Part 5 dbg

11

Suffixes For Floating-Point Numbers

• Numeric values assigned to variables of floating-point types must have specific suffixes to avoid compiler errors.

• Any floating-point number is automatically regarded as a double; it is denoted with a d suffix.

• Add the f suffix to make the floating-point number a float (single).

• Add the m suffix to make the floating-point number a decimal.

Page 12: Variables, Calculations, Formatting Numbers, and Catching Errors Part 5 dbg

Variable Scope

Page 13: Variables, Calculations, Formatting Numbers, and Catching Errors Part 5 dbg

13

Variable Scope

• Access to variables can be controlled by where you declare them.

• Variables declared within a class (ex. form), but outside any other programming block of the class are available anywhere in the class (class scope); declare class scope variables outside of methods/functions.

• Variables declared within a programming block, such as within a method/function, are only available in that block (local or block scope).

VariableScopes

Page 14: Variables, Calculations, Formatting Numbers, and Catching Errors Part 5 dbg

14

Hiding a Class Variable

• If a block scope variable has the same name as a class scope variable, the value of the local variable will “hide” the value of the class variable within the block.

• The original value of the class scope variable remains intact outside the block.

• To eliminate confusion, don’t use the same variable name within 2 different scopes.

VariableHiding

Page 15: Variables, Calculations, Formatting Numbers, and Catching Errors Part 5 dbg

15

Parsing Numbers from Strings

• Even though we may intend a TextBox to allow entry of a numeric value, anything typed in a TextBox becomes a string value.

• Numeric values may be “extracted” from the string with the Parse() method of one of the numeric types.

• The Convert class has methods that perform conversions as well.

ParseInteger

int age = Convert.ToInt32(txtAge.Text);

int age = int.Parse(txtAge.Text);

Page 16: Variables, Calculations, Formatting Numbers, and Catching Errors Part 5 dbg

Math

Simple Operations

Page 17: Variables, Calculations, Formatting Numbers, and Catching Errors Part 5 dbg

17

Operators and Operands

• A math operation involves a math operator working with at least one operand.

• Operands are either variables or constants.• The result of the operation is often assigned to

another variable.• The = sign represents the assignment operator.

Page 18: Variables, Calculations, Formatting Numbers, and Catching Errors Part 5 dbg

18

Operators

+ Addition a + b

- Subtraction a - b

* Multiplication a * b

/ Division a / b

% Remainder a % b

- Unary negative -a

+ Unary positive +a

Page 19: Variables, Calculations, Formatting Numbers, and Catching Errors Part 5 dbg

19

Operator Precedence

• Operators within parentheses are applied first; start with the innermost parenthesis of a nest.

• Unary operators are applied next; multiple unary operators applied left to right.

• Multiplication, division and remainder are applied next; multiple operators applied left to right.

• Addition and subtraction operators applied last; multiple operators applied left to right.

• These rules are commonly called “Order of Operations”.

Precedence

Page 20: Variables, Calculations, Formatting Numbers, and Catching Errors Part 5 dbg

20

Assignment Operators

• Instead of:counter = counter + 1;

• You can use:counter++;

• Instead of:number = number + 5;

• You can use:number += 5;

• Likewise there are other shortcut assignment operators:

-= *= /=

Page 21: Variables, Calculations, Formatting Numbers, and Catching Errors Part 5 dbg

21

Assignment Operators

Operator Sample Explanation

+= a += 5; a = a + 5;

-= b -= 4; b = b – 4;

*= c *= k + 1; c = c * (k + 1);

/= d /= 2; d = d / 2;

++(increment)

k++; k = k + 1;

--(decrement)

m--; m = m - 1;

Page 22: Variables, Calculations, Formatting Numbers, and Catching Errors Part 5 dbg

22

Assignment Operators

• The += assignment operator works with string variables, as well as with numeric variables.

lblMessage.Text = “”; //empty string

lblMessage.Text += “Hello, ”;

lblMessage.Text += txtFirst.Text + “ ” + txtLast.Text;

lblMessage.Text += “. How are you today?”;

• If I type my name in the TextBoxes, the code above would display the following text in lblMessage Label.

Hello, Dee Gudmundsen. How are you today?

AssignOps

Page 23: Variables, Calculations, Formatting Numbers, and Catching Errors Part 5 dbg

23

Converting from One Numeric Data Type to Another

• Certain value types may be converted to others more directly using casting.

• In the example below, notice the different use of parentheses between casting with C++ and casting with C#.

• Truncation may take place when floating point values are cast to integer values.

• ANSI values result when char variables are cast to int variables.

CastingmyInt = (int) myDouble;

Page 24: Variables, Calculations, Formatting Numbers, and Catching Errors Part 5 dbg

Outputting Variable Values

Page 25: Variables, Calculations, Formatting Numbers, and Catching Errors Part 5 dbg

25

Displaying a Constant Value

• We can display the value of a string type constant by assigning it to the Text Property of a Label control at run time because the Text Property is of type string.

StringConstant

Page 26: Variables, Calculations, Formatting Numbers, and Catching Errors Part 5 dbg

26

Displaying a Variable Value

• We can display initial values of variables.• We can assign new values to variables and

display them as well.• String variables can be assigned directly to the

Text Property of a Textbox or Label.

StringVariable

Page 27: Variables, Calculations, Formatting Numbers, and Catching Errors Part 5 dbg

27

Displaying Numeric Values

• Values stored in variables with types other than string must be converted to strings before assigning them to a string variable or a Text Property.

• Variables of other types all have a ToString() method for this conversion.

NumericVariables

Page 28: Variables, Calculations, Formatting Numbers, and Catching Errors Part 5 dbg

28

Rounding

• Use the Round(), Ceiling() or Floor() methods of the Math class for various types of rounding.

Rounding

double myNum = double.Parse(txtNumIn.Text);

lblInt.Text = ((int) myNum).ToString();

lblRoundUp.Text = Math.Ceiling(myNum).ToString();

lblRoundDown.Text = Math.Floor(myNum.ToString();

lblRound.Text = Math.Round(myNum).ToString();

Page 29: Variables, Calculations, Formatting Numbers, and Catching Errors Part 5 dbg

29

Changing the Format of Numeric Values While Outputting

• You can specify a format for the output string by placing a format specifier within () of the ToString() method.

decimal extendedPrice = 109.8765d;

lblPrice.Text = extendedPrice.ToString(“C”);

• These statements display the extended price as money in lblPrice.

displays as $109.88

FormatSpecifiers1

Page 30: Variables, Calculations, Formatting Numbers, and Catching Errors Part 5 dbg

30

Format Specifiers

CCurrency: $, commas, 2 decimal places; (500) for negative

E Scientific notation in powers of 10

FFixed # decimal places (2 by default), no commas, -500 for negative

G General; E or F chosen on basis of length

NThousands separated by commas; 2 decimal places by default; -500 for negative

PPercent: %, 2 decimal places by default, -500 for negative

Page 31: Variables, Calculations, Formatting Numbers, and Catching Errors Part 5 dbg

31

Write Code to Format the Output

1. A calculated variable named averagePay has a value of 123.456 and should display in lblAvgPay.

2. The variable idNumber, which contains 176123 must be displayed in lblEmpID without commas.

3. The total amount collected in a fund drive is being accumulated in a variable named totalCollected. Write a statement that will display the variable in lblTotal with commas and two decimal places but no dollar signs?

Page 32: Variables, Calculations, Formatting Numbers, and Catching Errors Part 5 dbg

Finding Errors

Writing Values to the Output Window

Page 33: Variables, Calculations, Formatting Numbers, and Catching Errors Part 5 dbg

33

Tracking Calculations with Debug

• The Debug object of the System.Diagnostics namespace has some useful methods for examining code while it is running.

• Running the WriteLine() method allows you to write information to the Output Window while the program is running.

Page 34: Variables, Calculations, Formatting Numbers, and Catching Errors Part 5 dbg

34

Tracking Calculations with Debug

• This represents a very quick way to peek into a running program and view the actual contents of variables without having to show them with controls.

DebugWriteLine

Page 35: Variables, Calculations, Formatting Numbers, and Catching Errors Part 5 dbg

Making Code User Error Proof

Try/Catch

Page 36: Variables, Calculations, Formatting Numbers, and Catching Errors Part 5 dbg

36

Trapping Run Time Errors

• Certain problems with data may cause a program to abnormally terminate or “crash” at run time.

• Code that could cause such problems can be “trapped”.

• Trapped code can be run in “trial mode” and rejected if actually completing the instructions could lead to a crash.

Page 37: Variables, Calculations, Formatting Numbers, and Catching Errors Part 5 dbg

37

Try/Catch Trap

• This is a simple structure that encloses the code within braces following the keyword try.

• If an error condition is encountered, code enclosed in braces following the keyword catch is executed.

• The code runs normally if no error condition exists.

Page 38: Variables, Calculations, Formatting Numbers, and Catching Errors Part 5 dbg

38

Try/Catch Trap

• Use a MessageBox or Label text in the catch portion of the trap to alert the user that the try code has resulted in an error.

• You should use a try/catch trap when attempting to parse a string for a numeric value. ParseTryCatch

try

{

int age = int.Parse(txtAge.Text);

}

catch

{

//feedback to user goes here

}

Page 39: Variables, Calculations, Formatting Numbers, and Catching Errors Part 5 dbg

39

Remember Try/Catch

• It is always a good idea to use try/catch traps when doing calculations on values from user input.

• You can retrieve a meaningful error message if you declare an object of type Exception in the catch.

• Run the Message() method of the Exception object and display in a MessageBox.

Exceptions

Page 40: Variables, Calculations, Formatting Numbers, and Catching Errors Part 5 dbg

Providing Feedback to User

The MessageBox

Page 41: Variables, Calculations, Formatting Numbers, and Catching Errors Part 5 dbg

41

Message Box Class

• Another class from the Framework Class Library.

• The object produced is a small, modal form, containing at least one button.

• A modal form can not lose focus until it is closed.• The MessageBox is closed with one of its

buttons.

Page 42: Variables, Calculations, Formatting Numbers, and Catching Errors Part 5 dbg

42

MessageBox Class Interface

• Run the Show() method to display a MessageBox object.

• Pass an informational message to the Show() method as a string type argument.

SimpleMessage

Page 43: Variables, Calculations, Formatting Numbers, and Catching Errors Part 5 dbg

43

MessageBox Class Interface

• No Properties are revealed for the MessageBox class; but we can customize the MessageBox by supplying additional arguments.

• It is possible to display a title bar caption, a meaningful icon, and a set of buttons, depending on the arguments passed to the Show() method.

• Intellisense displays a descriptive prompt for the list of optional arguments.

Page 44: Variables, Calculations, Formatting Numbers, and Catching Errors Part 5 dbg

44

Argument Lists

• Any time we run a method/function with arguments, Intellisense will display a prompt that describes them.

Page 45: Variables, Calculations, Formatting Numbers, and Catching Errors Part 5 dbg

45

Multiple Argument Lists

• Sometimes, as in the case of the MessageBox Show() method, the underlying method/function may have more than one argument list.

• We say that the method presents multiple interfaces or signatures.

• Intellisense allows us to choose which argument list we want to use for the method.

Page 46: Variables, Calculations, Formatting Numbers, and Catching Errors Part 5 dbg

46

Overloaded Functions

• The term overloaded method/function is used when there are multiple versions of a method/function (with the same name, but with different argument lists).

• All the signatures of all of the overloaded methods appear in Intellisense.

Page 47: Variables, Calculations, Formatting Numbers, and Catching Errors Part 5 dbg

47

Adding a Caption

• A second argument sends a string type caption that will appear in the title bar of the MessageBox “form”.

MessageCaption

Page 48: Variables, Calculations, Formatting Numbers, and Catching Errors Part 5 dbg

48

Returning a Value

• So far, the versions of the Show() method we have run have represented void methods/functions.

• Including the buttons argument to the list requires that the MessageBox be used as a method/function that returns a value.

Page 49: Variables, Calculations, Formatting Numbers, and Catching Errors Part 5 dbg

49

Returning a Value

• The user causes a different constant to be returned, depending upon the button used to close the MessageBox.

Page 50: Variables, Calculations, Formatting Numbers, and Catching Errors Part 5 dbg

50

Buttons Arguments

• Several different patterns of buttons may be added to the MessageBox.

• Intellisense provides a list of the available values for the argument.

MessageButtons

Page 51: Variables, Calculations, Formatting Numbers, and Catching Errors Part 5 dbg

51

Icon Arguments

• Special icons can be added to emphasize the meaning of a MessageBox.

• Requires an additional argument.• MessageBox icons can be identified as providing

general information, questions, important information and warnings.

Page 52: Variables, Calculations, Formatting Numbers, and Catching Errors Part 5 dbg

52

Icon Arguments

• Intellisense provides a list of the available values for the argument.

MessageIcons

Page 53: Variables, Calculations, Formatting Numbers, and Catching Errors Part 5 dbg

53

A local recording studio rents its facilities for $200 per hour, but charges only for the number of minutes used. Your form should allow input of the name of the group and the number of minutes used in the studio. Your program should calculate (and display) the recording charge for this session, as well as accumulate the total charges for all groups.

Display summary information in a group box. Display the total charges for all groups, the total number of groups, and the average charge per group. Format all output appropriately. Include Calculate, Clear for Next Group (does not clear summary info), and Exit buttons. Do not allow bad input to cancel the program.