540 likes | 633 Views
Variables, Calculations, Formatting Numbers, and Catching Errors. Part 5 dbg. Built-in Value Data Types. Built-in Integer Data Types . Built-in Floating-Point Data Types . Other Built-in Value Data Types . Built-in Reference Data Type . Variables.
E N D
Variables, Calculations, Formatting Numbers, and Catching Errors Part 5 dbg
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-typeidentifier; decimal grossPay; int age; bool latePayment; string firstName; • Use camel casing for multi-word variable identifiers.
Named Constants • Use a namedconstant 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.
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;
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;
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.
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
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
Extracting Numbers from Strings • Even though we may intend a TextBox to allow entry of a numeric value, anything typed in a TextBoxis stored in the Text property ofTextBox,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); ParseInteger Use class names from Slide 3-4 with Convert class.
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.
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 Operations”. Precedence
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: -=*=/=
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
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;
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
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
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
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
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
Write Code to Format the Output • A calculated variable named averagePay has a value of 123.456 and should display in lblAvgPay. • The variable idNumber, which contains 176123 must be displayed in lblEmpID without commas. • 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?
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
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
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.
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.
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
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
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.
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
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.
Argument Lists • Any time we run a method/function with arguments, Intellisense will display a prompt that describes them.
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.
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.
Adding a Caption • A second argument sends a string type caption that will appear in the title bar of the MessageBox “form”. MessageCaption
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.
Returning a Value • The user causes a different constant to be returned, depending upon the button used to close the MessageBox.
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