Brief description on how to navigate within this presentation (ppt)

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.
Objectives Understand the software development lifecycle Perform calculations Use decision structures Perform data validation Use logical operators Use.
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
Chapter 3: Introducing the Microsoft.NET Framework and Visual Basic.NET Visual Basic.NET Programming: From Problem Analysis to Program Design.
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.
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.
Chapter 3: Using Variables and Constants
Programming with Microsoft Visual Basic th Edition CHAPTER THREE USING VARIABLES AND CONSTANTS.
Variables, Constants, and Calculations
3-1 aslkjdhfalskhjfgalsdkfhalskdhjfglaskdhjflaskdhjfglaksjdhflakshflaksdhjfglaksjhflaksjhf.
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.
Introduction to Java Applications Part II. In this chapter you will learn:  Different data types( Primitive data types).  How to declare variables?
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.
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 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 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.
3-1 aslkjdhfalskhjfgalsdkfhalskdhjfglaskdhjflaskdhjfglaksjdhflakshflaksdhjfglaksjhflaksjhf.
Programming with Microsoft Visual Basic th Edition
110 E-1 Variables, Constants and Calculations(2) Chapter 3: Operations on variables, scope of a variable, formatting data Doing Arithmetic.
Variables and Expressions Programming Right from the Start with Visual Basic.NET 1/e 7.
Microsoft Visual Basic 2012 CHAPTER FOUR Variables and Arithmetic Operations.
CIS 338: VB Variables Dr. Ralph D. Westfall April, 2011.
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.
Lecture 3: More Java Basics Michael Hsu CSULA. Recall From Lecture Two  Write a basic program in Java  The process of writing, compiling, and running.
Representing Data: Constants and Variables
Microsoft Visual Basic 2010 CHAPTER FOUR Variables and Arithmetic Operations.
A variable is a name for a value stored in memory.
Chapter 2 Variables.
Topics Designing a Program Input, Processing, and Output
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.
BASIC ELEMENTS OF A COMPUTER PROGRAM
Chapter 2 - Introduction to C Programming
Data Types, Arithmetic Operations
2.5 Another Java Application: Adding Integers
Variables and Arithmetic Operations
Chapter 3: Using Variables and Constants
Variables, Expressions, and IO
Chapter 2 - Introduction to C Programming
Variables and Arithmetic Operations
IDENTIFIERS CSC 111.
Visual Basic Programming Chapter Four Notes Working with Variables, Constants, Data Types, and Expressions GROUPBOX CONTROL The _____________________________________.
CIS16 Application Development Programming with Visual Basic
Chapter 2 Variables.
Visual Basic Numbers Chapter 3.3 Prepared By: Deborah 1/15/2019.
Introduction to Visual Basic
Topics Designing a Program Input, Processing, and Output
Topics Designing a Program Input, Processing, and Output
Primitive Types and Expressions
Unit 3: Variables in Java
Chapter 2 Variables.
Introduction to C Programming
Visual Basic Numbers Chapter 3.3 Prepared By: Deborah 7/9/2019.
Brief description on how to navigate within this presentation (ppt)
Presentation transcript:

aslkjdhfalskhjfgalsdkfhalskdhjfglaskdhjflaskdhjfglaksjdhflakshflaksdhjfglaksjhflaksjhf Brief description on how to navigate within this presentation (ppt) The first time a Key Term from the chapter is used in the ppt it will display in blue Gold colored text boxes display coding examples Slides will be numbered (# of #) when multiple slides on same topic (Slide title) Speaker notes are included where appropriate for slides (*)Denotes either a comment for page reference to textbook or slide reference in ppt

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

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

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

Data - Variables and Constants (1 of 2) 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 When you declare a variable or a named constant, VB reserves an area of memory and assigns it a name, called an identifier Identifier names are specified according to the rules of Basic as well as some recommended naming conventions

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

Data Types Data Type Use For Storage Size in bytes Boolean True or False value 2 Byte 0 to 255, binary data 1 Clear Single Unicode character Date 1/1/0001 through 12/31/9999 8 Decimal Decimal fractions, such as dollars/cents 16 Single Single precision floating-point numbers with six digits of accuracy 4 Double Double precision floating-point numbers with 14 digits of accuracy Short Small integer in the range -32,768 to 32,767 Integer Whole numbers in the range -2,147,483,648 to +2,147,483,647 Long Larger whole numbers String Alphanumeric data: letters, digits, and other characters Varies Object Any type of data The data type of a variable or constant indicates what type of information will be stored in the allocated memory space The data type charts displays the kind of data each type of data types hold, and the amount of memory allocated for each

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 A programmer has to name (identify) the variables and named constants that will be used in a project

Constants Named User assigned name, data type and value Use CONST keyword to declare Const COMPANY_ADDRESS_String As String = "101 S. Main Street" Const SALES_TAX_RATE_Decimal As Decimal = .08D Constants provide a way to use words to describe a value that doesn’t change Constants are declared using the keyword and are given a name, a data type, and a value Once a value is declared as a constant, its value can’t be changed during the execution of the project Data type declared and data type of the value must match Many sets of intrinsic constants (key term) are declared in system class libraries and are available for use in VB programs

Assigning Values to Constants Declare the data type of numeric constants by appending a type-declaration character Decimal D Decimal – 850.50D Double R Double – 52875.8R Integer I Integer – 12345678I Long L Long – 134257987L Short S Single F Single – 101.25F If a type-declaration character is not appended any whole number is assumed to be Integer and any fractional value is assumed to be Double Use two quotes with a string literal to avoid confusion

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

Declaration Statement Examples Dim customerName Strging As String As String Private totalSoldInteger As Integer As Integer Dim temperatureSingle As Single Dim priceDecimal As Decimal Private priceDecimal VB IntelliSense feature helps you enter Private, Public, and Dim statements—after you type the space that follows VariableName As, a list pops up and displays the possible entries for data type to complete the statement If you begin to complete the statement the list automatically scrolls to the correct section; when the correct entry is highlighted press Enter, Tab, or the spacebar to select the entry or double-click if using the mouse The reserve word Dim is really short dimension, which means size. When declaring a variable, the amount of memory reserved depends on its data type.

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 A variable may exist and be visible for an entire project, for only one form, or for only one procedure Visibility really means “this variable can be used or ‘seen’ in this location.” Namespace - Available to all procedures of project Module - Available to all procedures within that module (often a form) Use Public or Private keywords Local - Available only to the procedure in which it is declared Block - Available only in block of code inside a procedure where declared An example of a module level variable declaration is displayed on the next slide (Slide 15)

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

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

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 The class that you use depends on the data type of the variable to which you are assigning a value; for example, to convert text to an integer, use the Integer.Parse method

Converting to String Values assigned to string variables or Text properties must be string Convert any numeric data type to string using .ToString method When you assign a value to a variable, you must take care to assign like types; you assign an integer value to an Integer variable and a decimal value to a Decimal variable ( chart shown on next slide, Slide 19) There are some exception to the rule about assigning only like types See “Implicit Conversions”

Conversion Methods Method Convert To Integer.Parse Integer Decimal.Parse Decimal .ToString String

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( )

Arithmetic Operations Operator Operation + Addition – Subtraction * Multiplication / Division \ Integer Division Mod Modulus – Remainder of division ^ Exponentiation The arithmetic operations you can perform you can perform in VB include addition, subtraction, multiplication, division, integer division, modulus, and exponentiation The first four operations are self explanatory, but you may not be familiar with Integer Division, Modulus, and/or exponentiation Integer division-use to divide one integer by another giving an integer result truncating (dropping) any remainder Modulus – returns the remainder of a division problem Exponentiation – raises a number to the pwer specified and retruns (produces) a result of the Double data type

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

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.

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

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

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 VB provides two options that can significantly change the behavior of the editor and compiler Not using either Option Explicit and/or Option Strict can make coding somewhat easier but provide opportunities for hard-to-find errors and very sloppy programming When Option Explicit is turned off, programmers can use any variable name without first declaring it which is a throwback to the older version of Basic and programmers spent many hours debugging programs that had small typos in a variable name Programmers should always program with Option Explicit turned on-in VB.NET the option is turned on by default for all new projects. Programmers will need to place a an additional code line before the first line of code in a file to turn it off When Option Strict it turned on, the editor and compiler try to help keep programmers from making hard-to-find mistakes. By having Option Strict turned on programmers can be saved from developing poor programming habits

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() When wanting to display numeric data in the Text property of a label or text box the value must first be converted to string—the data can be formatted which controls the way the output will look

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 The format specifier codes formats the display of output and are predefined The default format of each of the formatting codes is based on the computer’s regional setting Format specifier codes are displayed on the next slide (Slide 32) and examples are shown on the following slide (Slide 33)

Format Specifier Codes Name C or c Currency F or f Fixed-point N or n Number D or d Digits P or p Percent

Format Specifier Code Examples Variable Value Code Output totalDecimal 1125.6744 "C" $1,125.67 "N0" 1,126 pinInteger 123 "D6" 000123 rateDecimal 0.075 "P" 7.50% "P3" 7.500% "P0" 8% valueInteger -10 ($10.00)

Date Specifier Code Format DateTime values using format codes and ToString method Date codes are case sensitive The strings returned are based on the computer’s regional settings and can be changed. Currently the default values are set for US-English in Windows XP *Refer to chart on p. 118

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) Two sample message boxes

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

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

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

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 Programs often need to calculate the sum of numbers. The technique for summing is to declare a module-level variable for the total