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
Description
Bytes
Storage
.NET
Class
byte
sbyte
positive integer between 0 and +255
1
Byte
signed integer value from -128 to +127
1
SByte
short
ushort
int
signed integer from -32,768 to 32,767
2
Int16
unsigned integer from 0 to +65,535
2
UInt16
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
3
Built-in Floating-Point Data Types
C#
keyword
Description
Bytes
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
4
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
5
Built-in Reference Data Type
C#
keyword
Description
Bytes
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
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 before it can be
used.
Syntax: data-type identifier;
decimal grossPay;
bool latePayment;
int age;
string firstName;
• Use camel casing for multi-word variable
identifiers.
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 SALES_TAX_RATE = 0.0825d;
const string 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.
• 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*/
this.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.5d;
10
Suffixes For Floating-Point Numbers
• Numeric values assigned to variables of floatingpoint 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 is controlled by where you
declare them.
• Variables declared within a class (ex. form), but
outside any other programming block
(methods/functions ) of the class are available
anywhere in the class (class scope).
• Variables declared within a programming block
(such as within a method/function or if/else) 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 variable
remains intact outside the block.
• To eliminate confusion, don’t use the same
variable name within 2 different scopes.
 VariableHiding
14
Extracting Numbers from Strings
• Even though we may intend a TextBox to allow
entry of a numeric value, anything typed in a
TextBox is stored in the Text property of
TextBox, and thus is a string.
• Numeric values may be “extracted” from the
string with the Parse() method of the desired
numeric type. The Convert class has methods
that perform conversions as well.
int age = int.Parse(txtAge.Text);
int age = Convert.ToInt32(txtAge.Text);
Use class names from Slide 3-4 with Convert class.
 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
a+b
-
Subtraction
a-b
*
Multiplication
a*b
/
Division
a/b
%
Remainder after
division
a%b
-
Unary negative
-a
+
Unary positive
+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 modulus 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
 Precedence
Operations”.
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
Sample
Explanation
+=
a += 5;
a = a + 5;
-=
b -= 4;
b = b – 4;
*=
c *= k + 1;
c = c * (k + 1);
/=
d /= 2;
d = d / 2;
++
k++;
k = k + 1;
m--;
m = m - 1;
(increment)
-(decrement)
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 text boxes, the code above
displays the following in lblMessage.
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.
 Casting
myInt = (int) myDouble;
23
Outputting Variable Values
Displaying a Constant Value
• We can display the value of a string constant by
assigning it to the Text Property of a Label
control at run time because the Text Property is
of type string.
 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() or Floor() methods
of the Math class 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
Currency: $, commas, 2 decimal places; (500) for
negative
E
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
Thousands separated by commas; 2 decimal
places by default; -500 for negative
P
Percent: %, 2 decimal places by default, -500 for
negative
30
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?
31
Finding Errors
Writing Values to the Output Window
Writing to the Output Window - 1
• One way to write some output to the Output
Window is:
System.Diagnostics.Debug.Writeline(desired output);
• Adding the following to the top of your code:
using System.Diagnostics;
allows you to shorten this to:
Debug.Writeline(desired output);
 DebugWriteLine
33
Writing to the Output Window - 2
• Another way to write some output to the Output
Window is:
Console.Writeline(desired output);
• Either System.Diagnostics.Debug.WriteLine() or
Console.Writeline() can be used as a quick way
to peek into a running program and view the
actual contents of variables without having to
display or format the values in controls.
 ConsoleWriteLine
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 in try 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 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.
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 will display a prompt that
describes them.
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 of the
MessageBox “form”.
 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