Presentation is loading. Please wait.

Presentation is loading. Please wait.

Chapter 3 Variables, Constants, and Calculations Copyright © 2011 by The McGraw-Hill Companies, Inc. All Rights Reserved. McGraw-Hill.

Similar presentations


Presentation on theme: "Chapter 3 Variables, Constants, and Calculations Copyright © 2011 by The McGraw-Hill Companies, Inc. All Rights Reserved. McGraw-Hill."— Presentation transcript:

1 Chapter 3 Variables, Constants, and Calculations Copyright © 2011 by The McGraw-Hill Companies, Inc. All Rights Reserved. McGraw-Hill

2 3-2 3- Objectives (1 of 2) Distinguish between variables, constants, and controls. Differentiate among the various data types. Apply naming conventions incorporating standards and indicating the data type. Declare variables and constants. Select the appropriate scope for a variable. Convert text input to numeric values.

3 3-3 3- Objectives (2 of 2) Perform calculations using variables and constants. Convert between numeric data types using implicit and explicit conversions. Round decimal values using the Decimal.Round method. Format values for output using the ToString method. Use Try/Catch blocks for error handling. Display message boxes with error messages. Accumulate sums and generate counts.

4 3-4 3- Data — Variables and Constants (1 of 2) Variable Memory locations that hold data that can be changed during project execution Example: customer’s name Named Constant Memory locations that hold data that cannot be changed during project execution Example: sales tax rate

5 3-5 3- Data — Variables and Constants (2 of 2) In Visual Basic, when you declare a Variable or Named Constant An area of memory is reserved A name is assigned called an Identifier Follow rules and naming conventions Use Declaration Statements to establish Variables and Constants, Assign name and data type, Not executable unless initialized on same line

6 3-6 3- Data Types Data TypeUse ForStorage Size in bytes BooleanTrue or False value2 Byte0 to 255, binary data1 ClearSingle Unicode character2 Date1/1/0001 through 12/31/99998 DecimalDecimal fractions, such as dollars/cents16 SingleSingle precision floating-point numbers with six digits of accuracy 4 DoubleDouble precision floating-point numbers with 14 digits of accuracy 8 ShortSmall integer in the range -32,768 to 32,7672 IntegerWhole numbers in the range -2,147,483,648 to +2,147,483,647 4 LongLarger whole numbers8 StringAlphanumeric data: letters, digits, and other charactersVaries ObjectAny type of data4

7 3-7 3- 3-7 Older Naming of Data Types Data TypePrefix Boolean bln Byte byt Character chr Date dtm Decimal dec Single sng Double dbl Short sht Integer int Long lng String str Object obj

8 3-8 3- Naming Variables and Constants Must follow Visual Basic Naming Rules Should follow Naming Conventions Meaningful names consisting of letters, digits, and underscores; must begin with a letter and no spaces or periods. Include class (data type) of variable (variable: countInteger constant: QUOTA_Integer) Use mixed case for variables and uppercase for constants (quantityInteger). Cannot use reserved words or keywords to which Basic has assigned a meaning, such as print, name, and value

9 3-9 3- Constants Named User assigned name, data type, and value Use CONST keyword to declare. Intrinsic System defined within Visual Studio (Color.Red) Const COMPANY_ADDRESS_String As String = "101 S. Main Street" Const SALES_TAX_RATE_Decimal As Decimal =.08D

10 3-10 3- Assigning Values to Constants DecimalDDecimal – 850.50D DoubleRDouble – 52875.8R IntegerIInteger – 12345678I LongLLong – 134257987L ShortSShort – 350S SingleFSingle – 101.25F Declare the data type of numeric constants by appending a type-declaration character.

11 3-11 3- Declaring Variables Declared inside a procedure using a Dim statement Declared outside a procedure using Public, Private, or Dim statements Always declare the variable’s data type. May declare several variables with one statement. Use IntelliSense to assist in writing statements.

12 3-12 3- Declaration Statement Examples Dim customerNameStringAs String Private totalSoldIntegerAs Integer Dim temperatureSingleAs Single Dim priceDecimalAs Decimal Private priceDecimalAs Decimal

13 3-13 3- Scope and Lifetime of Variables (1 of 2) Visibility of a variable is its scope. Scope may be Namespace Module level Local Block level Lifetime of a variable is the period of time the variable exists.

14 3-14 3- Module Level Variable Declaration Example Code module-level declarations in the Declaration section at the top of the code.

15 3-15 3- Variable Definition (Declarations section) Const NamedConstants Private ModuleLevelVariables Private Sub CalculateButton_Click Dim LocalVariables … End Sub Private Sub SummaryButton_Click Dim LocalVariables … End Sub Private Sub ClearButton_Click Dim LocalVariables … End Sub

16 3-16 3- Guidelines for User Input Each Input object (textbox, etc) and Output object (label, textbox, etc.) will have its own variable associated with it Input object requires that its value be captured, that is to convert it from text to a numeric value and placed in a variable All calculations (formulas) will be done ONLY with variables, constants and functions; the results of all calculations will be placed in a variable All variables will be formatted into an output object (label, textbox, etc.) in order to make them visible and appear in user friendly format

17 3-17 3-

18 3-18 3- Option Explicit and Option Strict Option Explicit forces variables to be declared before using. Option Strict Makes VB a strongly typed language like C++, Java and C# Does not allow implicit conversions from a wider data type to a narrower one or between String and numeric data types Best practice to always turn both on either in code or in Project Properties dialog box

19 3-19 3- Converting Between Numeric Data Types Implicit (automatic) conversion Converts value from narrower data type to wider type where no danger of losing precision exists Explicit conversion (casting) Uses methods of Convert class to convert between data types Convert Class has methods that begin with “To” for each of the data types.

20 3-20 3- Performing Calculations with Unlike Data Types VB performs the calculations using the wider data type. Use a cast if converting the result to a different data type. Example: Convert.ToInt32(CountInteger / NumberDecimal) or Convert.ToSingle(CountInteger / NumberDecimal). VB does not convert to a different data type until it is necessary.

21 3-21 3- Converting Strings to a Numeric Data Type Use Parse methods to convert the Text property to its numeric form before it’s used in a calculation. Each numeric data type class has a Parse method. Parse method returns a value that can be used in calculations. Parse method fails if user enters nonnumeric data or leaves data blank.

22 3-22 3- Conversion Methods MethodConvert To Integer.ParseInteger Decimal.ParseDecimal.ToStringString

23 3-23 3- Conversion Examples QuantityInteger =Integer.Parse(quantityTextBox.Text) PriceDecimal =Decimal.Parse(priceTextBox.Text) WholeNumberInteger =Integer.Parse(digitString) ResultTextBox.Text =ResultDecimal.ToString( ) CountTextBox.Text =CountInteger.ToString( ) IDString =IDInteger.ToString( )

24 3-24 3- Calculations Calculations can be performed with variables, constants, properties of certain objects, and numeric literals. Do not use strings in calculations. Values from Text property of Text Boxes Are strings, even if they contain numeric data Must be converted to a numeric data type before performing a calculation

25 3-25 3- Arithmetic Operations OperatorOperation +Addition –Subtraction *Multiplication /Division \Integer Division ModModulus – Remainder of division ^Exponentiation

26 3-26 3- Order of Operations Hierarchy of operations, or order of precedence, in arithmetic expressions from highest to lowest 1. Any operation inside parentheses 2. Exponentiation 3. Multiplication and division 4. Integer division 5. Modulus 6. Addition and subtraction

27 3-27 3- Evaluation of Expression 1. All operations within parentheses. Multiple operations within the parentheses are performed according to the rules of precedence. 2. All exponentiation. Multiple exponentiation operations are performed from left to right. 3. All multiplication and division. Multiple operations are performed from left to right. 4. All integer division. Multiple operations are performed from left to right. 5. Mod operations. Multiple operations are performed from left to right. 6. All addition and subtraction are performed from left to right.

28 3-28 3- Mathematical Examples Note the use of parentheses to control order of precedence. 3+4*2 = 11Multiply then add (3+4)*2 = 14Parentheses control: add then multiply 8/4*2 = 4Same level, left to right: divide then multiply

29 3-29 3- Using Calculations in Code Perform calculations in assignment statements. What appears on right side of assignment operator is assigned to item on left side. Assignment operators — allows shorter versions of code =, +=, -=, *=, /=, \=, &= ‘Accumulate a total. TotalSalesDecimal += salesDecimal

30 3-30 3- Rounding Numbers Round decimal fractions Decimal.Round method returns a decimal result rounded to a specified number of decimal positions. Decimal.Round and Convert methods use technique called “rounding toward even.” Decimal Value to Round Number of Decimal PositionsResults 1.45521.46 1.44521.44 1.502 2.502

31 3-31 3- Converting to String Values assigned to string variables or Text properties must be string. Convert any numeric data type to string using.ToString method. Examples: ResultTextBox.Text = ResultDecimal.ToString() CountTextBox.Text = CountInteger.ToString() IDString = IDInteger.ToString()

32 3-32 3- Formatting Data for Display To display numeric data in a label or text box, first convert value to string. Use ToString method Format the data using formatting codes. Specifies use of dollar sign, percent sign, and commas Specifies number of digits that appear to right of decimal point DisplayTextBox.Text = NumberInteger.ToString()

33 3-33 3- Using Format Specifier Codes "C" code Currency — String formatted with dollar sign, commas separating each group of 3 digits and 2 digits to the right of decimal point "N" code Number — String formatted with commas separating each group of 3 digits and 2 digits to the right of decimal point Can specify number of decimal positions Example: "C0" zero digits

34 3-34 3- Format Specifier Codes Name C or cCurrency F or fFixed-point N or nNumber D or dDigits P or pPercent

35 3-35 3- Format Specifier Code Examples VariableValueCodeOutput totalDecimal1125.6744"C""C"$1,125.67 totalDecimal1125.6744"N0"1,126 pinInteger123"D6"000123 rateDecimal0.075"P""P"7.50% rateDecimal0.075"P3"7.500% rateDecimal0.075"P0"8% valueInteger-10"C""C"($10.00)

36 3-36 3- Date Specifier Code Format DateTime values using format codes and ToString method.

37 3-37 3- Counting and Accumulating Sums Declare module-level variables, since local level variables reset to 0 each time the procedure is called. Summing Numbers Counting Calculating an Average DiscountedPriceSumDecimal += DiscountedPriceDecimal Private saleCountInteger As Integer saleCountInteger += 1 AverageDiscountedSaleDecimal = DiscountedPriceSumDecimal / SaleCountInteger

38 3-38 3- Chapter 3 – Problem Definition You are to create a program that allows a user to enter the quantity of a specific book, its title, and price. When the user presses the calculate button, then display the extended price (quantity * price), the amount of the 15% discount, and the discounted price (extended price – discount). When the user presses the Clear Sales button, clear all input and results and allow the user to start another sale. Round where appropriate.

39 3-39 3-

40 3-40 3- Handling Exceptions Use structured exception handling to easily catch errors before run-time error occurs. Catching exceptions is referred to as error trapping. Coding to handle exception is called error handling. Error handling in Visual Studio.NET is standardized for all languages using the Common Language Runtime, CLR, which improves on previous versions of VB.

41 3-41 3- Try/Catch Blocks Enclose statements that might cause an error within Try/Catch block. If an exception occurs while statements in the Try block are executing, program control is transferred to the Catch Block. If a Finally statement is included, the code in that section executes last, whether or not an exception occurred.

42 3-42 3- Try Block — General Form Try ‘statements that may cause an error Catch [VariableName As ExceptionType] ‘statements for action when an exception occurs [Finally ‘statements that always execute before exit of the Try block] End Try

43 3-43 3- Try Block — Example Catches Any Exception Try QuantityInteger = Integer.Parse(QuantityTextBox.Text) QuantityTextBox.Text = QuantityInteger.ToString( ) Catch MessageLabel.Text = "Error in input data." End Try

44 3-44 3- Try Block — Example Catches Specific Exception This Catch statement catches bad input data that cannot be converted to numeric. Catch theException As FormatException MessageLabel.Text="Error in input data." End Try

45 3-45 3- Common Exception Classes Each exception is an instance of the Exception class. The properties of this class allow you to determine the code location of the error, the type of error, and cause.

46 3-46 3- Try Block — Example Handling Multiple Exceptions Catch TheException As FormatException ' Statements for nonnumeric data. Catch TheException As ArithmeticException ' Statements for calculation problem. Catch TheException As Exception ' Statements for any other exception.

47 3-47 3- MessageBox Object (1 of 2) The MessageBox is an overloaded method. Signatures correspond to the argument list. There are multiple signatures to choose from. Do not reverse, transpose, or leave out any of the arguments. IntelliSense displays argument list (also called signatures). MessageBox.Show (TextMessage, TitlebarText, _ MessageBoxButtons, MesssageBoxIcon)

48 3-48 3- MessageBox Object (2 of 2) TextMessage string String literal or variable that displays message Title Bar text String that appears in title bar of message box MessageBox Buttons OK, OKCancel, RetryCancel, YesNo, YesNoCancel, AbortRetryIgnore MessageBox Icons Asterisk, Error, Exclamation, Hand, Information, None, Question, Stop, Warning

49 3-49 3- Using Overloaded Methods This OOP feature allows the Show method to act differently for different arguments. Each argument list is called a signature so the Show method has several signatures. Supplied arguments must exactly match one of the signatures provided by the method. IntelliSense in Visual Studio editor helps when entering arguments so that they don’t need to be memorized.

50 3-50 3- Testing Multiple Fields Each input field presents an opportunity for an exception. To indicate specific fields that caused the exception, use nested Try/Catch blocks. Pinpoints specific errors, and after error, sets focus back to field in error Use SelectAll method of text box to make text appear selected to aid user.

51 3-51 3- Chapter 3 – Problem Definition You are to create a program that allows a user to enter the quantity of a specific book, its title, and price. When the user presses the calculate button, then display the extended price (quantity * price), the amount of the 15% discount, and the discounted price (extended price – discount). When the user presses the Clear Sales button, clear all input and results and allow the user to start another sale. Round where appropriate. Prevent the user from entering non-numeric data into the Quantity and Price fields. Additionally, the Quantity field should not allow non-integer values. Use a message box to notify the user when an error occurs. Provide for the following output to be updated after each transaction: Total Number of Books Total Discount Given Total Discounted Amount Average Discount

52 3-52 3- Nested Try/Catch blocks Try ' Convert quantity to numeric variable. QuantityInteger = Integer.Parse(QuantityTextBox.Text) Try ' Convert price if quantity was successful. PriceDecimal = Decimal.Parse(PriceTextBox.Text) ' Calculate values for sale. Catch PriceException As FormatException ' Handle a price exception. MessageBox.Show("Price must be numeric.", "Data Entry Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation) With PriceTextBox.Focus().SelectAll() End With End Try Catch QuantityException As FormatException ' Handle a quantity exception. MessageBox.Show("Quantity must be numeric.", "Data Entry Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation) With QuantityTextBox.Focus().SelectAll() End With End Try

53 3-53 3- Testing Multiple Fields – Method 2 Use separate Try/Catch for each field At the end of the Catch code, use Exit Sub to terminate processing and return control to the field in error

54 3-54 3- Separate Try/Catch blocks Try ' Convert quantity to numeric variable. QuantityInteger = Integer.Parse(QuantityTextBox.Text) Catch QuantityException As FormatException ' Handle a quantity exception. MessageBox.Show("Quantity must be numeric.", "Data Entry Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation) With QuantityTextBox.Focus().SelectAll() End With Exit Sub End Try Try ' Convert price if quantity was successful. PriceDecimal = Decimal.Parse(PriceTextBox.Text) Catch PriceException As FormatException ' Handle a price exception. MessageBox.Show("Price must be numeric.", "Data Entry Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation) With PriceTextBox.Focus().SelectAll() End With Exit Sub End Try ' Calculate values for sale.


Download ppt "Chapter 3 Variables, Constants, and Calculations Copyright © 2011 by The McGraw-Hill Companies, Inc. All Rights Reserved. McGraw-Hill."

Similar presentations


Ads by Google