3-1 aslkjdhfalskhjfgalsdkfhalskdhjfglaskdhjflaskdhjfglaksjdhflakshflaksdhjfglaksjhflaksjhf.

Slides:



Advertisements
Similar presentations
Lecture Set 4 Data Types and Variables Part B – Variables, Constants, Expressions Conversion Rules Options Strict, Option Explicit Scope of Definition.
Advertisements

Chapter 3 Variables, Constants, and Calculations Copyright © 2011 by The McGraw-Hill Companies, Inc. All Rights Reserved. McGraw-Hill.
Data Types in Java Data is the information that a program has to work with. Data is of different types. The type of a piece of data tells Java what can.
Variables, Constants, and Calculations. Data — Variables and Constants (1 of 2) Variable  Memory locations that hold data that can be changed during.
Chapter 3 Variables, Constants, and Calculations
Data types and variables
IS437: Fall 2004 Instructor: Dr. Boris Jukic Data Types, Constants, Variables, Scope, Conversion.
Chapter 2 Data Types, Declarations, and Displays
Chapter 3: Introducing the Microsoft.NET Framework and Visual Basic.NET Visual Basic.NET Programming: From Problem Analysis to Program Design.
CSci 142 Data and Expressions. 2  Topics  Strings  Primitive data types  Using variables and constants  Expressions and operator precedence  Data.
Chapter Three Using Variables and Constants Programming with Microsoft Visual Basic th Edition.
Chapter 3 Variables, Constants, and Calculations Copyright © 2011 by The McGraw-Hill Companies, Inc. All Rights Reserved. McGraw-Hill.
1 Chapter Two Using Data. 2 Objectives Learn about variable types and how to declare variables Learn how to display variable values Learn about the integral.
Variables, Constants, Methods, and Calculations Chapter 3 - Review.
Objectives You should be able to describe: Data Types
Chapter 3 Variables, Constants, and Calculations Programming in C#.NET © 2003 by The McGraw-Hill Companies, Inc. All rights reserved.
Variables and Constants
McGraw-Hill © 2009 The McGraw-Hill Companies, Inc. All rights reserved. Chapter 3 Variables, Constants, and Calculations.
McGraw-Hill © 2009 The McGraw-Hill Companies, Inc. All rights reserved. Chapter 3 Variables, Constants, and Calculations.
Variables, Constants, and Calculations
Chapter 3: Using Variables and Constants
Programming with Microsoft Visual Basic th Edition CHAPTER THREE USING VARIABLES AND CONSTANTS.
Visual Basic 2010 How to Program © by Pearson Education, Inc. All Rights Reserved.
Variables, Constants, and Calculations
Introduction to Visual Basic. Introduction In this chapter, we introduce Visual Basic programming with program code. We demonstrate how to display information.
Arithmetic operations and operators, converting data types and formatting programs for output. Year 11 Information Technology.
Chapter 2: Using Data.
Microsoft Visual Basic 2005 CHAPTER 4 Variables and Arithmetic Operations.
Chapter 4 Variables and constants. 4.1 Variables -Use of variables is good programming style -easier to modify -easier for a programmer to understand.
Visual Basic IITG to be expanded. What is Visual Basic? Object Oriented Programming Language (OOP) Graphical User Interface (GUI) Event Driven – Write.
Variables, Constants, and Calculations. Calculations Although the calculations themselves are quite simple (addition, subtraction, multiplication, and.
Object-Oriented Program Development Using Java: A Class-Centered Approach, Enhanced Edition.
Microsoft Visual Basic 2005: Reloaded Second Edition Chapter 3 Variables, Constants, Methods, and Calculations.
Chapter 3 P. 1 Data - Variables and Constants Definition A variable is a value which can change during program execution. A constant is a value which can.
Chapter 3 Variables, Constants and Calculations Programming In Visual Basic.NET.
Variables & Function Calls. Overview u Variables  Programmer Defined & Intrinsic  Data Types  Calculation issues u Using Functions  The val() function.
Chapter 2 Variables.
Microsoft Visual Basic 2010: Reloaded Fourth Edition Chapter Three Memory Locations and Calculations.
Chapter 3 w Variables, constants, and calculations DIM statements - declaration temporary memory locations identifier, data type, scope data types - values.
Chapter 4 Variables and constants. 4.1 Variables -Use of variables is good programming style -easier to modify -easier for a programmer to understand.
Variables and Constants Variable Memory locations that hold data that can be changed during project execution Example: a customer’s name Constant Memory.
Programming with Microsoft Visual Basic 2008 Fourth Edition Chapter Three Using Variables and Constants.
Exceptions, handling exceptions & message boxes Year 11 Information Technology.
Operators and Expressions. 2 String Concatenation  The plus operator (+) is also used for arithmetic addition  The function that the + operator performs.
3-1 aslkjdhfalskhjfgalsdkfhalskdhjfglaskdhjflaskdhjfglaksjdhflakshflaksdhjfglaksjhflaksjhf.
Programming with Microsoft Visual Basic th Edition
Variables Hold information that may be manipulated, used to manipulate other information or remembered for later use A storage location in memory (RAM)
McGraw-Hill © 2010 The McGraw-Hill Companies, Inc. All rights reserved. Chapter 3 Variables, Constants and Calculations.
110 E-1 Variables, Constants and Calculations(2) Chapter 3: Operations on variables, scope of a variable, formatting data Doing Arithmetic.
CHAPTER THREE Representing Data: Constants and Variables.
Microsoft Visual Basic 2012 CHAPTER FOUR Variables and Arithmetic Operations.
Chapter 3: Introducing the Microsoft.NET Framework and Visual Basic.NET Visual Basic.NET Programming: From Problem Analysis to Program Design.
Making Interactive Programs with Visual Basic .NET
Chapter 4.  Variables – named memory location that stores a value.  Variables allows the use of meaningful names which makes the code easier to read.
Slide 1 Chapter 3 Variables  A variable is a name for a value stored in memory.  Variables are used in programs so that values can be represented with.
Instructors: Sidra Ehsan Budoor Bawazeer CpCS 206.
© 2006 Lawrenceville Press Slide 1 Chapter 4 Variables  A variable is a name for a value stored in memory.  Variables are created using a declaration.
Slide 1 Chapter 3 Variables  A variable is a name for a value stored in memory.  Variables are created using a declaration statement. For example: Dim.
Microsoft Visual Basic 2010 CHAPTER FOUR Variables and Arithmetic Operations.
A variable is a name for a value stored in memory.
Chapter 3: Variables, Constants, and Calculations
Arithmetic operations and operators, converting data types and formatting programs for output. Year 11 Information Technology.
An Application Uses Variables to Hold Information So It May Be Manipulated, Used to Manipulate Other Information, or Remembered for Later Use.
Variables and Arithmetic Operations
Variables and Arithmetic Operations
Brief description on how to navigate within this presentation (ppt)
Visual Basic Numbers Chapter 3.3 Prepared By: Deborah 1/15/2019.
Introduction to Visual Basic
Visual Basic Numbers Chapter 3.3 Prepared By: Deborah 7/9/2019.
Brief description on how to navigate within this presentation (ppt)
Presentation transcript:

3-1 aslkjdhfalskhjfgalsdkfhalskdhjfglaskdhjflaskdhjfglaksjdhflakshflaksdhjfglaksjhflaksjhf

Variables, Constants and Calculations Chapter 3 3 McGraw-Hill© 2006 The McGraw-Hill Companies, Inc. All rights reserved.

3-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-4 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

3-5 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

3-6 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

3-7 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 characters Varies ObjectAny type of data4

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

3-9 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 (QUOTA_Integer) Use mixed case for variables and uppercase for constants (quantityInteger) Can not use reserved words or keywords that Basic has assigned a meaning such as print, name, and value

3-10 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

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

3-12 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

3-13 Declaration Statement Examples Dim customerNameString As StringAs String Private totalSoldInteger As IntegerAs Integer Dim temperatureSingle As SingleAs Single Dim priceDecimal As DecimalAs Decimal Private priceDecimal As DecimalAs Decimal

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

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

Chapter 4: Variables and Arithmetic Operations 16 Guidelines for User Input Each Input object (textbox, etc) and Output object (label, textbox, etc.) will have its own variable associated with it 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

Chapter 4: Variables and Arithmetic Operations 17

3-18 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

3-19 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

3-20 Converting to String Values assigned to string variables or Text properties must be string Convert any numeric data type to string using.ToString method

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

3-22 Conversion Examples quantityInteger =Integer.Parse(quantityTextBox.Text) priceDecimal =Decimal.Parse(priceTextBox.Text) wholeNumberInteger =Integer.Parse(digitString) resultLabel.Text =resultDecimal.ToString( ) countTextBox.Text =countInteger.ToString( ) idString =idInteger.ToString( )

Chapter 4: Variables and Arithmetic Operations 23 Converting Variable Data A procedure to convert a String data type to an Integer data type is named ToInt32 The procedure is found in the Convert class, which is available in a Visual Studio 2005 class library quantityInteger =Convert.ToInt32(quantityTextBox.Text) priceDecimal=Convert.ToDec(priceTextBox.Text) wholeNumberInteger=Convert.ToInt32(digitString)

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

3-25 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

3-26 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.

3-27 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

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

3-29 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 on either in code or in Project Properties dialog box

3-30 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

3-31 Performing Calculations with Unlike Data Types VB performs the calculations using the wider data type Perform a cast if converting the result to a different data type VB does not convert to a different data type until it is necessary

3-32 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

3-33 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 Me.displayTextBox.Text = numberInteger.ToString()

3-34 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

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

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

3-37 Date Specifier Code Format DateTime values using format codes and ToString method Date codes are case sensitive (p. 118)

Modified Problem Definition(1) 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. 3-38

Modified Problem Definition() 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 3-39

Chapter 3: Program Design and Coding 40 OIP (1) OUTPUT Extended Price Discount Discounted Price Total Number of Books Total Discount Given Total Discounted Amounts Average Discount INPUT Quantity Title Price

Chapter 3: Program Design and Coding 41 OIP PROCESS Capture input (quantity, price) Calculate extended price Calculate discount Round discount Calculate discounted price Display results Clear input and results Send focus to Clear Sales button Send focus to Quantity Exit program Calculate Totals Display Totals

Chapter 3: Program Design and Coding 42 OEA OBJECTEVENTTASK(S) Exit buttonClickExit program Clear ButtonClickClear input Clear results Send focus to Quantity Calculate buttonClickCapture input (quantity, price) Calculate extended price Calculate discount Round discount Calculate discounted price Display results Send focus to Clear Sales button Calculate Totals Display Totals

3-43 Handling Exceptions Use structured exception handling to easily catch errors before run-time error occurs Catching exceptions referred to as error trapping Coding to handle exception 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

3-44 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

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

3-46 Try Block - Example Catches Any Exception Try quantityInteger = Integer.Parse(quantityTextBox.Text) Me.quantityLabel.Text = quantityInteger.ToString( ) Catch Me.messageLabel.Text = "Error in input data." End Try

3-47 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

3-48 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.

3-49 Try Block - Example Handling Multiple Exceptions Try ' Statements that may cause errors. 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. End Try

3-50 MessageBox Object (1 of 2) MessageBox.Show (TextMessage, TitlebarText, _ MessageBoxButtons, MesssageBoxIcon) 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)

3-51 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

3-52 Using Overloaded Methods This OOP feature allows the Show method to act differently for different arguments Each argument list if 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

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

3-54 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

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. 3-55

Chapter 3: Program Design and Coding 56 OIP OUTPUT Extended Price Discount Discounted Price INPUT Quantity Title Price PROCESS Capture input (quantity, price) Calculate extended price Calculate discount Round discount Calculate discounted price Display results Clear input Clear results Send focus to Clear Sales button Send focus to Quantity Exit program

Chapter 3: Program Design and Coding 57 OEA (1) OBJECT Exit button EVENT Click TASK Exit program OBJECT Clear Button EVENT Click TASK Clear input Clear results Send focus to Quantity

Chapter 3: Program Design and Coding 58 OEA (2) OBJECT Calculate button EVENT Click TASK Capture input (quantity, price) Calculate extended price Calculate discount Round discount Calculate discounted price Display results Send focus to Clear Sales button