Title: Variables, Calculations, Formatting Numbers, and Catching Errors
1Variables, Calculations, Formatting Numbers, and
Catching Errors
2Primitive Data Types
3Data Types (See table on page 85)
int whole numbers in the range 2.1billion 4 bytes
long whole numbers in the range 9.2E18 8 bytes
float floating point numbers (6 digits of precision) 4 bytes
double floating point numbers with greater range and precision (14 digits of precision) 8 bytes
bool Boolean values, TRUE or FALSE 1 byte
string alphanumeric data letters, numbers, punctuation varies
char single Unicode character 2 bytes
byte 0 to 255, binary data 1 byte
decimal monetary values with accurate rounding (28 digits of precision) 16 bytes
4Variables
- 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. The declaration must consist of the data
type the variable will store and a legal
identifier. - decimal grossPay int age
- bool latePayment string firstName
- Use camel casing for variable identifiers, but do
not use data type prefixes, as in textbook.
5Named 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.
6Intrinsic 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
7Initialization 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.
8Suffixes For Real Numbers
- Numeric values assigned to variables of certain
real types must have specific suffixes to avoid
compiler errors. - Any real (non integer numeric) number is
automatically regarded as a double it is denoted
with a d suffix. - Add the f suffix to make the real number a float
(single). - Add the m suffix to make the real number a
decimal.
9Variable Scope
10Variable Scope (See pg 93)
- 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
functions. - Variables declared within a programming block,
such as within a function, are only available in
that block (local or block scope).
? VariableScopes
11Hiding 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. - This is not a recommended practice.
? VariableHiding
12Parsing 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.
? ParseInteger
13Math
14Operators 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.
15Operators
Addition a b
- Subtraction a - b
Multiplication a b
/ Division a / b
Remainder a b
- Unary negative -a
Unary positive a
16Operator Precedence
- Operators within parentheses are applied first
the innermost parenthesis of a nest. - Unary operators applied next multiple unary
operators applied left to right. - Multiplication, division and remainder 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
17Assignment Operators
- Instead of the following statement
- counter counter 1
- You can use the following statement
- counter
- Instead of the following statement
- number number 5
- You can use the following statement
- number 5
- Likewise there are other shortcut assignment
operators - - /
18Assignment 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 (increment)
-- m-- m m -1 (decrement)
19Assignment 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
20Converting 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
21Outputting Variable Values
22Displaying 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
23Displaying 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
24Displaying 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()
function for this conversion.
? NumericVariables
25Rounding
- Use the Round(), Ceiling() or Floor() methods of
the Math class for various types of rounding. - The Round() method uses a technique called
rounding toward even.
? Rounding
26Changing the Format of Numeric Values While
Outputting
- You can specify a specific 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 the Price label. - displays as 109.88
? FormatSpecifiers1
27Format Specifiers (See pg 102)
C Currency using local settings with 2 decimal places
E Scientific notation in powers of 10
F Fixed decimal places 2 by default
G General E or F chosen on basis of length
N Thousands separated by commas 2 decimal places by default
P Percent
28Lets Try Some Output Specifiers
- Page 103, Feedback 3.6, questions 1-3
29Finding Errors
- Writing Values to the Output Window
30Tracking 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.
31Tracking 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
32Making Code User Error Proof
33Trapping 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.
34Try/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.
35Try/Catch Trap
- Although coding the Catch portion of the trap is
not required, a standard technique is to use a
MessageBox or Label text to alert the user that
the Try has resulted in an error. - Parsing a string for a numeric value is an
excellent candidate for a Try/Catch trap.
? ParseTryCatch
36Remember 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
37Providing Feedback to User
38Message 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.
39MessageBox 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
40MessageBox Class Interface
- No Properties are revealed for the MessageBox
class but we can customize the MessageBox by
supplying additional arguments or parameters. - 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.
41Argument Lists
- Any time we run a function with arguments,
Intellisense will display a prompt that describes
them.
42Multiple Argument Lists
- Sometimes, as in the case of the MessageBox
Show() method, the underlying 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.
43Overloaded Functions
- The term overloaded function is used when there
are multiple versions of a function (with the
same name, but with different argument lists). - All the signatures of all of the overloaded
function appear in Intellisense.
44Adding a Caption
- A second argument sends a string type caption
that will appear in the title bar of the
MessageBox form.
? MessageCaption
45Returning a Value
- So far, the versions of the Show() method we have
run have represented void functions. - Including the buttons argument to the list
requires that the MessageBox be used as a
function that returns a value.
46Returning a Value
- The user causes a different constant to be
returned, depending upon the button used to close
the MessageBox.
47Buttons Arguments
- Several different patterns of buttons may be
added to the MessageBox. - Intellisense provides a list of the available
values for the argument.
? MessageButtons
48Icon 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.
49Icon Arguments
- Intellisense provides a list of the available
values for the argument.
? MessageIcons