10.07.2015 Views

Variables and Constants - TATI

Variables and Constants - TATI

Variables and Constants - TATI

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

BCS 2123 Visual ProgrammingNamed <strong>Constants</strong> - 2• Two advantages to using– Easier to read• MAXIMUM_PAY_Decimal more meaningful than1000• To change value, change constant declarationonce, not every reference in code• const Statement – Examplesconst string COMPANY_ADDRESS_String = “101 S. Main Street”;const decimal SALES_TAX_RATE_Decimal = .08m;McGraw-Hill © 2010 The McGraw-Hill Companies, Inc. All rights reserved. 3-13Assigning Values to <strong>Constants</strong> - 1• Numeric constants– May contain only digits (0-9)– Decimal point– Sign at the left side (+ or -)– Type declaration character at the right side (optional)– Cannot contain comma, dollar sign, any other specialcharacters, sign (+ or -) at right side– Use type declaration character to specify the datatype• Without type declaration character,whole numbers assumed to be int<strong>and</strong> fractional values assumed to bedoubledecimaldoublelongshortfloatM or mD or dL or lS or sF or fMcGraw-Hill © 2010 The McGraw-Hill Companies, Inc. All rights reserved. 3-14Assigning Values to <strong>Constants</strong> - 2• String constants (or literals)– Enclose in quotes– Can contain letters, digits, <strong>and</strong> specialcharacters– To include a quotation mark within a literal,precede the quotation mark with a backslash(\)"He said, \“I like it.\" "produces the string: He said, “I like it."Intrinsic <strong>Constants</strong>• System-defined constants• Declared in system class libraries• Specify class name or group name <strong>and</strong>constant name– Example – Color.Red is the constant “Red” inthe class “Color”McGraw-Hill © 2010 The McGraw-Hill Companies, Inc. All rights reserved. 3-15McGraw-Hill © 2010 The McGraw-Hill Companies, Inc. All rights reserved. 3-16Declaring <strong>Variables</strong> - 1• Declare a variable– Specify data type <strong>and</strong> follow with anidentifier– Assign an initial value (optional)string customerNameString;string customerNameString = “None”;private int totalSoldInteger;int totalSoldInteger = 0;float temperatureFloat;float temperatureFloat = 32f;decimal priceDecimal;private decimal priceDecimal = 99.95m;Declaring <strong>Variables</strong> - 2• Declare several variables in one statement– Data type at beginning of statement applies toall variables in statement– Separate variable names with commas– End statement with a semicolon (;)string nameString, addressString, phoneString;decimal priceDecimal, totalDecimal;int countInteger = 0, totalInteger = 0;McGraw-Hill © 2010 The McGraw-Hill Companies, Inc. All rights reserved. 3-17McGraw-Hill © 2010 The McGraw-Hill Companies, Inc. All rights reserved. 3-18


BCS 2123 Visual ProgrammingInitializing Numeric <strong>Variables</strong>• Must assign a value before use– Variable must appear on left side of equalsign before used on right side of equal sign• Initialize a variable when declaredint quantityInteger = 0;• Or declare variable <strong>and</strong> assign value laterint quantityInteger;quantityInteger = int.Parse(quantityTextBox.Text);Entering Declaration Statements• IntelliSense helps in entering declarationstatements– Type correct entry– List scrolls to correct section– When correct entry is highlighted• Press Enter, Tab, or spacebar or double-click entrywith mouseMcGraw-Hill © 2010 The McGraw-Hill Companies, Inc. All rights reserved. 3-19McGraw-Hill © 2010 The McGraw-Hill Companies, Inc. All rights reserved. 3-20Scope <strong>and</strong> Lifetime of <strong>Variables</strong>• Visibility of a variable is its scope– Namespace• Also referred to as global– Class-level– Local– Block• Scope of variable determined by where itis declaredVariable Lifetime• Period of time a variable exists– Local or block variable• One execution of a method• After execution variables disappear, memorylocations are released– Class-level variable• Entire time class is loaded (usually lifetime ofproject)• <strong>Variables</strong> maintain value for multiple executions ofa methodMcGraw-Hill © 2010 The McGraw-Hill Companies, Inc. All rights reserved. 3-21McGraw-Hill © 2010 The McGraw-Hill Companies, Inc. All rights reserved. 3-22Local Declarations• Variable declared inside a method is localin scope– Known only to that method• Must be declared prior to first use– All declarations should appear at the top of amethod (after comments)• All constants should be declared at classlevel– Easy to locate to facilitate any changesClass-Level Declarations• <strong>Variables</strong> declared at class level can beused anywhere in that form’s class• Place after opening brace for class,outside of any methodClass variables<strong>and</strong> constantsMcGraw-Hill © 2010 The McGraw-Hill Companies, Inc. All rights reserved. 3-23McGraw-Hill © 2010 The McGraw-Hill Companies, Inc. All rights reserved. 3-24


BCS 2123 Visual ProgrammingRounding Numbers• Round decimal fractions using decimal.Round– Returns a decimal result rounded to the specified number ofdigits// Round to two decimal positions.resultDecimal = decimal.Round(amountDecimal, 2);• decimal.Round <strong>and</strong> Convert methods use "roundingtoward even" if the digit to the right of the final digit isexactly 5.Decimal value to roundNumber of decimalpositionsResult1.455 2 1.461.445 2 1.441.5 0 22.5 0 2Formatting Data for Display• Display numeric data in a label or text boxby converting the value to a string– Use ToString methoddisplayTextBox.Text = numberInteger.ToString();• Format the data using formatting codes asan argument of the ToString method– Specifies dollar sign, percent sign, <strong>and</strong>commas– Specifies the number of digits to the right ofthe decimal pointMcGraw-Hill © 2010 The McGraw-Hill Companies, Inc. All rights reserved. 3-43McGraw-Hill © 2010 The McGraw-Hill Companies, Inc. All rights reserved. 3-44Using Format Specifier Codes - 1• "C" or "c" – Currency– String formatted with a dollar sign, commas separating eachgroup of three digits, <strong>and</strong> two digits to the right of the decimalpointextendedpriceTextBox.Text = (quantityInteger * priceDecimal).ToString("C");• "N" or "n" – Number– String formatted with commas separating each group of threedigits, two digits to right of the decimal pointdiscountTextBox.Text = discountDecimal.ToString("N");• Specify number of decimal positions by placing anumeric digit following the specifier codediscountTextBox.Text = discountDecimal.ToString("N3");Using Format Specifier Codes - 2• Additional Format Specifier Codes– "F" or "f" – Fixed point• String of numeric digits, no commas, two decimal places,minus sign at left for negative values– "D" or "d" – Digits• Force a specified number of digits to display• For integer data types only, minus sign at left– "P" or "p" – Percent• Multiplies the value by 100, adds a space <strong>and</strong> a percent sign,rounds to two decimal places– Additional codes for dates <strong>and</strong> times• d, D, t, T, f, F, g, G, m, M, r, R• Date <strong>and</strong> time codes are case sensitiveMcGraw-Hill © 2010 The McGraw-Hill Companies, Inc. All rights reserved. 3-45McGraw-Hill © 2010 The McGraw-Hill Companies, Inc. All rights reserved. 3-46Choosing the Controlsfor Program Output• Output can display in labels or text boxes– Labels – Cannot be changed by the user• Used traditionally for program output– Text boxes – Can be changed by the user• To use for output– Set ReadOnly property to true (BackColor property changes toControl)– Set TabStop property to false– Set BorderStyle property to Fixed3D or FixedSingle• Advantages over using labels for output– Text boxes do not disappear when cleared– Form layout looks more uniform– The clipboard Copy comm<strong>and</strong> is available to the userFormat Specifier Code ExamplesVariableValueFormat SpecifierCodeOutputtotalDecimal 1125.6744 "C" $1,125.67totalDecimal 1125.6744 "N" 1,125.67totalDecimal 1125.6744 "N0" 1,126balanceDecimal 1125.6744 "N3" 1,125.674balanceDecimal 1125.6744 "F0" 1126pinInteger 123 "D6" 000123rateDecimal 0.075 "P" 7.50 %rateDecimal 0.075 "P3" 7.500 %rateDecimal 0.075 "P0" 8 %valueInteger –10 "C" ($10.00)valueInteger –10 "N" – 10.00valueInteger –10 "D3" – 010McGraw-Hill © 2010 The McGraw-Hill Companies, Inc. All rights reserved. 3-47McGraw-Hill © 2010 The McGraw-Hill Companies, Inc. All rights reserved. 3-48


BCS 2123 Visual ProgrammingH<strong>and</strong>ling Exceptions• Exceptions cause run-time errors– Blank or non-numeric data cause Parse methods tofail– Entering a number that results in an attempt to divideby zero• Exception H<strong>and</strong>ling catches bad data before arun-time error occurs– Writing code to catch exceptions is called exceptionh<strong>and</strong>ling– Exception h<strong>and</strong>ling in Visual Studio.NET isst<strong>and</strong>ardized for all languages that use the CLRtry/catch Blocks• Enclose any statement(s) that might causean error in a try/catch block– If an exception occurs while the statements inthe try block are executing, program controltransfers to the catch block– The code in a finally block (if included)executes last, whether or not an exceptionoccurredMcGraw-Hill © 2010 The McGraw-Hill Companies, Inc. All rights reserved. 3-49McGraw-Hill © 2010 The McGraw-Hill Companies, Inc. All rights reserved. 3-50The try Block – General FormThe try Block - Example• try• {• // Statements that may cause error.• }• catch [(ExceptionType [VariableName])]• {• // Statements for action when exception occurs.• }• [finally• {• // Statements that always execute before exit of tryblock.• }]• Write different catch statements to specify thetype of exception to catch• This catch will catch any exceptiontry{quantityInteger = int.Parse(quantityTextBox.Text);quantityTextBox.Text = quantityInteger.ToString();}catch{messageLabel.Text = "Error in input data.";}McGraw-Hill © 2010 The McGraw-Hill Companies, Inc. All rights reserved. 3-51McGraw-Hill © 2010 The McGraw-Hill Companies, Inc. All rights reserved. 3-52The Exception Class - 1• Each exception is an instance of theException class– The properties of this class allow theprogrammer to:• Determine the code location of the error• Determine the type <strong>and</strong> cause of the error• The Message property contains a text messageabout the error• The Source property contains the name of theobject causing the errorThe Exception Class - 2• Include the text message associatedwith the exception• Declare a variable name in the catchstatement for the exceptioncatch (FormatException theException){messageLabel.Text = "Error in input data: " theException.Message;}McGraw-Hill © 2010 The McGraw-Hill Companies, Inc. All rights reserved. 3-53McGraw-Hill © 2010 The McGraw-Hill Companies, Inc. All rights reserved. 3-54


BCS 2123 Visual ProgrammingH<strong>and</strong>ling Multiple Exceptions - 1• Include multiple catch blocks (h<strong>and</strong>lers)• Catch statements are checked in sequence• First one with a matching exception is used• Same variable name can be used for multiplecatch statements– Variable’s scope is only that block– Omit variable name for exception if no need to refer toproperties of the exception object in the catch blockH<strong>and</strong>ling Multiple Exceptions - 2catch (FormatException theException){// Statements for nonnumeric data.}catch (ArithmeticException theException){// Statements to h<strong>and</strong>le calculation problem.}catch (Exception theException){// Statements for any other exception.}McGraw-Hill © 2010 The McGraw-Hill Companies, Inc. All rights reserved. 3-55McGraw-Hill © 2010 The McGraw-Hill Companies, Inc. All rights reserved. 3-56Displaying Messages in Message Boxes• Display a message in a message box– User has entered invalid data– User neglects to enter required data• Specify message, optional icon, title bar text <strong>and</strong>buttons• Use Show method of the MessageBox object todisplay a message boxThe MessageBox Object –General Form• Arguments must match one of the formats• Do not reverse, transpose or leave out anyargumentMessageBox.Show(TextMessage);MessageBox.Show(TextMessage, TitlebarText);MessageBox.Show(TextMessage, TitlebarText, MessageBoxButtons);MessageBox.Show(TextMessage, TitlebarText, MessageBoxButtons, MessageBoxIcon);McGraw-Hill © 2010 The McGraw-Hill Companies, Inc. All rights reserved. 3-57McGraw-Hill © 2010 The McGraw-Hill Companies, Inc. All rights reserved. 3-58The TextMessage String• TextMessage String– String literal enclosed in quotes– String variable– May concatenate several items• i.e. Combine a literal with a variable value– If message is too long, will wrap to next lineThe Titlebar Text• TitlebarText– Appears in the title bar of message box– If no TitlebarText argument, title bar willappear emptyMcGraw-Hill © 2010 The McGraw-Hill Companies, Inc. All rights reserved. 3-59McGraw-Hill © 2010 The McGraw-Hill Companies, Inc. All rights reserved. 3-60


BCS 2123 Visual ProgrammingMessageBox Buttons• Specify button(s) to display– Use the MessageBoxButtons constants ofMessageBox class• OK (default)• OKCancel• RetryCancel•YesNo• YesNoCancel• AbortRetryIgnoreMessageBoxIcon• IntelliSense pops up with complete list• <strong>Constants</strong> for MessageBoxIcon– Asterisk– Error–Exclamation– H<strong>and</strong>– Information– None– Question– Stop– WarningMcGraw-Hill © 2010 The McGraw-Hill Companies, Inc. All rights reserved. 3-61McGraw-Hill © 2010 The McGraw-Hill Companies, Inc. All rights reserved. 3-62Using Overloaded Methods• Overloading allows the Show method toact differently for different arguments• Each argument list is called a signature– The Show method has several signatures• Supplied arguments must exactly matchone of the signatures• IntelliSense helps in entering thearguments (no need to look up ormemorize the signatures)Testing Multiple Fields• Each input field presents an opportunityfor an exception• To indicate the field that caused the error,nest one try/catch block inside anotheroneMcGraw-Hill © 2010 The McGraw-Hill Companies, Inc. All rights reserved. 3-63McGraw-Hill © 2010 The McGraw-Hill Companies, Inc. All rights reserved. 3-64Nested try/catch Blocks - 1Nested try/catch Blocks - 2• One try/catch block completely contained insideanother one is a nested try/catch block– Nest as deeply as needed– Place calculations within the most deeply nested try• Do not perform calculations unless all input values areconverted without an exception– Test each Parse method• Specify which field caused error <strong>and</strong> set focus back to field inerror• Use SelectAll method of text box– Makes text appear selected to aid userMcGraw-Hill © 2010 The McGraw-Hill Companies, Inc. All rights reserved. 3-65try // Outer try block for the first field.{// Convert first field to numeric.try // Inner try block for the second field.{// Convert second field to numeric.// Perform the calculations for the fields that passed conversion.}catch (FormatException secondException){// H<strong>and</strong>le any exceptions for the second field.// Display a message <strong>and</strong> reset the focus for the second field.}// End of inner try block for the second field.}catch (FormatException firstException){// H<strong>and</strong>le exceptions for the first field.// Display a message <strong>and</strong> reset the focus for the first field.}McGraw-Hill © 2010 The McGraw-Hill Companies, Inc. All rights reserved. 3-66

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!