1 / 53

Variables, Calculations, 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 . Built-in Floating-Point Data Types . Other Built-in Value Data Types . Built-in Reference Data Type . Variables.

aysel
Télécharger la présentation

Variables, Calculations, Formatting Numbers, and Catching Errors

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


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

  2. Built-in Value Data Types

  3. Built-in Integer Data Types

  4. Built-in Floating-Point Data Types

  5. Other Built-in Value Data Types

  6. Built-in Reference Data Type

  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-typeidentifier ; decimal grossPay; int age; bool latePayment; string firstName; • Use camel casing for multi-word variable identifiers.

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

  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;

  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;

  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.

  12. Variable Scope

  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

  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

  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. int age = int.Parse(txtAge.Text); int age = Convert.ToInt32(txtAge.Text);  ParseInteger

  16. Math Simple Operations

  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.

  18. Operators

  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

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

  21. Assignment Operators

  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

  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. myInt = (int) myDouble;  Casting

  24. Outputting Variable Values

  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

  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

  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

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

  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

  30. Format Specifiers

  31. 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?

  32. Finding Errors Writing Values to the Output Window

  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.

  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

  35. Making Code User Error Proof Try/Catch

  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.

  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.

  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. try { int age = int.Parse(txtAge.Text); } catch { //feedback to user goes here }  ParseTryCatch

  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

  40. Providing Feedback to User The MessageBox

  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.

  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

  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.

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

  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.

  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.

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

  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.

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

  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

More Related