Variables, Assignment, Formatting Numbers, and Catching Errors

Download Report

Transcript Variables, Assignment, Formatting Numbers, and Catching Errors

Variables, Calculations, Formatting Numbers, and Catching Errors

Part 5

dbg

Built-in Value Data Types

Built-in Integer Data Types

C# keyword

byte sbyte short ushort int uint

Description

positive integer between 0 and +255 signed integer value from -128 to +127 signed integer from -32,768 to 32,767 unsigned integer from 0 to +65,535 signed integer from -2,147.483,648 to +2,147.483,647 unsigned integer from 0 to +4,294,967,295 long ulong signed integer from -9,223,372,036,854,775,808 to +9,223,372,036,854,775,807 unsigned integer from 0 to +18,446,744,073,709,551,615

Bytes Storage

1

.NET Class

Byte 1 2 2 4 4 8 8 SByte Int16 UInt16 Int32 UInt32 Int64 UInt64 3

Built-in Floating-Point Data Types

C# keyword

float double decimal

Description

floating point numbers (6 digits of precision) floating point numbers with greater range and precision (14 digits of precision) monetary values with accurate rounding (28 digits of precision)

Bytes Storage

4

.NET Class

Single 8 Double 16 Decimal 4

Other Built-in Value Data Types

C# keyword

bool

Description

a true or false value char a single Unicode character; designate a char value with single quotes

Bytes Storage

1

.NET Class

Boolean 2 Char 5

Built-in Reference Data Type

C# keyword

string object

Description

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

Bytes Storage

Varies

.NET Class

String Varies Object 6

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

used. before it can be Syntax:

data-type identifier

; decimal grossPay; int age; bool latePayment; • Use

camel casing

identifiers.

string firstName; for multi-word variable 7

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 const string SALES_TAX_RATE = 0.0825d; STATE = “NY”; • Named constants are typically declared before other variables in your program.

8

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; 9

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; 10

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 .

11

Variable Scope

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 13

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

remains intact outside the block.

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

 VariableHiding 14

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.

int age = int.Parse(txtAge.Text); int age = Convert.ToInt32(txtAge.Text);  ParseInteger 15

Math

Simple Operations

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 .

17

Operators

+ * / % + Addition Subtraction Multiplication Division Remainder Unary negative Unary positive a + b a - b a * b a / b a % b -a +a 18

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 19

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: -= *= /= 20

Assignment Operators

Operator

+= -= *= /= ++

(increment)

--

(decrement)

Sample

a += 5; b -= 4; c *= k + 1; d /= 2; k++; m--;

Explanation

a = a + 5; b = b – 4; c = c * (k + 1); d = d / 2; k = k + 1; m = m - 1; 21

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 22

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.

myInt = (int) myDouble;  Casting 23

Outputting Variable Values

Displaying a Constant Value

• We can display the value of a

string

type constant by assigning it to the Text Property Label control at run time because the Text Property is of type

string .

of a  StringConstant 25

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 26

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 27

Rounding

• Use the Round() , Ceiling() of the Math class or Floor() methods for various types of 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();  Rounding 28

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 29

Format Specifiers

C E Currency: $, commas, 2 decimal places; (500) for negative Scientific notation in powers of 10 F Fixed # decimal places (2 by default), no commas, -500 for negative G General; E or F chosen on basis of length N P Thousands separated by commas; 2 decimal places by default; -500 for negative Percent: %, 2 decimal places by default, -500 for negative 30

Write Code to Format the Output

1. A calculated variable named averagePay value of 123.456

and should display in has a 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? 31

Finding Errors

Writing Values to the Output Window

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 running.

while the program is 33

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 34

Making Code User Error Proof

Try/Catch

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.

36

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.

37

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.

try { int age = int.Parse(txtAge.Text); } catch { //feedback to user goes here }  ParseTryCatch 38

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 39

Providing Feedback to User

The MessageBox

Message Box Class

• Another class from the Framework Class Library.

• The object produced is a small,

modal

containing at least one button.

form, • A

modal

form can not lose

focus

until it is closed.

• The

MessageBox

is closed with one of its buttons.

41

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 42

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.

43

Argument Lists

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

will display a prompt that 44

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.

45

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 .

46

Adding a Caption

• A second argument sends a string type

caption

that will appear in the title bar MessageBox “form”.

of the  MessageCaption 47

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.

48

Returning a Value

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

MessageBox .

49

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 50

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.

51

Icon Arguments

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

 MessageIcons 52

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.

53