Chapter 3 Variables, Constants and Calculations Programming In Visual Basic.NET.

Slides:



Advertisements
Similar presentations
L2:CSC © Dr. Basheer M. Nasef Lecture #2 By Dr. Basheer M. Nasef.
Advertisements

Lecture Set 4 Data Types and Variables Part B – Variables, Constants, Expressions Conversion Rules Options Strict, Option Explicit Scope of Definition.
Chapter 3 Variables, Constants, and Calculations Copyright © 2011 by The McGraw-Hill Companies, Inc. All Rights Reserved. McGraw-Hill.
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
IS437: Fall 2004 Instructor: Dr. Boris Jukic Data Types, Constants, Variables, Scope, Conversion.
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.
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.
CHAPTER THREE Representing Data: Constants and Variables.
Chapter 3 Part 11 Variables, Constants, and Calculations Chapter 3 Section 3.3 Chapter 3 Section 3.4.
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.
Chapter 5 Using Data and COBOL Operators. Initializing Variables When you define a variable in WORKING- STORAGE, you also can assign it an initial value.
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?
CH2 – Using Data. Constant Something which cannot be changed Data Type Format and size of a data item Intrinsic Data Types Pg. 47 – Table 2-1 Basic ones.
Chapter 4 Variables and constants. 4.1 Variables -Use of variables is good programming style -easier to modify -easier for a programmer to understand.
Microsoft Visual Basic 2005: Reloaded Second Edition Chapter 3 Variables, Constants, Methods, and Calculations.
Applications Development
Copyright Curt Hill Variables What are they? Why do we need them?
Variables & Function Calls. Overview u Variables  Programmer Defined & Intrinsic  Data Types  Calculation issues u Using Functions  The val() function.
Chapter 2 Variables.
Variable, Constants and Calculations Dr Mohammad Nabil Almunawar.
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.
Chapter 3 Variables ( 變數 ), Constants ( 常數 ) and Calculations ( 計算 ) Programming In Visual Basic.NET Prepared by Johnny Tsui,
Exceptions, handling exceptions & message boxes Year 11 Information Technology.
1 Chapter 3 – Examples The examples from chapter 3, combining the data types, variables, expressions, assignments, functions and methods with Windows controls.
3-1 aslkjdhfalskhjfgalsdkfhalskdhjfglaskdhjflaskdhjfglaksjdhflakshflaksdhjfglaksjhflaksjhf.
Hungarian Notation A must in this course Every object used MUST be renamed including the form(s) using the following rules Form  frmFormName E.g. frmTemperature.
Programming with Microsoft Visual Basic th Edition
Visual Basic.NET Comprehensive Concepts and Techniques Chapter 4 Working with Variables, Constants, Data Types, and Expressions.
Variables Hold information that may be manipulated, used to manipulate other information or remembered for later use A storage location in memory (RAM)
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.
Week 6: THE C# LANGUAGE Flow Control. Slide 2 Data Types Boolean Byte (0 to 255) Char Date String Decimal Object Short (-32,768 to 32,767) Integer (-2,147,483,648.
CIS 338: VB Variables Dr. Ralph D. Westfall April, 2011.
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.
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
1.
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
CIS16 Application Development Programming with Visual Basic
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
CHAPTER FOUR VARIABLES AND CONSTANTS
Visual Basic Variables
Visual Basic Numbers Chapter 3.3 Prepared By: Deborah 7/9/2019.
Brief description on how to navigate within this presentation (ppt)
Presentation transcript:

Chapter 3 Variables, Constants and Calculations Programming In Visual Basic.NET

© 2001 by The McGraw-Hill Companies, Inc. All rights reserved Variables & Constants Variable –Memory locations that hold data that can be changed during project execution –Ex: hours worked Named Constant –Memory locations that hold data that cannot be changed during project execution –Ex: Sales tax percentage

© 2001 by The McGraw-Hill Companies, Inc. All rights reserved Constants Named –User defined Intrinsic –System defined within Visual Studio –In Chapter 23 we used the Intrinsic Color Constants

© 2001 by The McGraw-Hill Companies, Inc. All rights reserved Declaration Variables and Named Constants must be declared before being used in code When you declare a Variable or Named Constant VB –Reserves an area of memory –Assigns it a name called an Identifier Declaration statements are coded either –Beginning of a procedure –General Declarations of a module

© 2001 by The McGraw-Hill Companies, Inc. All rights reserved Declaration Statements DIM used to declare Variables CONST used to declare Named Constants Declaration includes –Name, follow Naming Convention Rules –Data Type –Required Value for Constants –Optional Initial Value for Variables

© 2001 by The McGraw-Hill Companies, Inc. All rights reserved Data Types (p 85 Table 3.1) Boolean Byte (0 to 255) Char Date String Decimal Object Short (-32,768 to 32,767) Integer (-2,147,483,648 to 2,147,483,647) Long (larger whole numbers) Single (floating point accuracy to 6 digits) Double (floating point accuracy to 14 points)

© 2001 by The McGraw-Hill Companies, Inc. All rights reserved Data Types – Memory Usage Boolean – 2 bytes Byte – 1 byte Char – 2 bytes Date – 8 bytes String – varies Decimal – 16 bytes Object – 4 bytes Short – 2 bytes Integer – 4 bytes Long – 8 bytes Single – 4 bytes Double – 8 bytes

© 2001 by The McGraw-Hill Companies, Inc. All rights reserved Data Types – Prefixes Boolean – bln Byte – byt Char – chr Date – dat String – str Decimal – dec Object – depends on type of object Short – sht Integer – int Long – lng Single – sng Double – dbl

© 2001 by The McGraw-Hill Companies, Inc. All rights reserved Dim strName, strSSN As String Dim intAge As Short Dim decPayRate As Decimal = 8.25 Dim datHireDate As Date Dim blnInsured As Boolean Dim lngPopulation As Long Const decDISCOUNT_RATE As Decimal =.15 Note: Constants are named using all uppercase letters EXCEPT the prefix. Declaration Examples

© 2001 by The McGraw-Hill Companies, Inc. All rights reserved Type-Declaration Characters Append single character to the end of the Constant's Value to indicate the Data Type Short – S Integer – I Long – L Decimal – D Single – F Double – R

© 2001 by The McGraw-Hill Companies, Inc. All rights reserved Variables – Scope & Lifetime Global/Public (use sparingly and cautiously) –Available to all modules and procedures of Project –Initialized at start of Project Module/Private (Form) –Available to one module and all procedures within that module –Initialized 1 st time the Form is loaded Local –Available only to the procedure it is declared in –Initialized every time the Procedure runs Block (not used until later in this course) –Available only to the block of code inside a procedure it is declared in –Initialized every time the Procedure runs

© 2001 by The McGraw-Hill Companies, Inc. All rights reserved Scope Declaring & Naming Global/Publicg prefix –Declare in General Declarations as Public Dim gstrName as String Module/Privatem prefix –Declare in Module’s General Declarations as Private Dim mstrName as String Localno prefix required –Declare in Event Procedures Dim strName as String

© 2001 by The McGraw-Hill Companies, Inc. All rights reserved Declaring Module Level Variables Example

© 2001 by The McGraw-Hill Companies, Inc. All rights reserved Calculations Calculations can be performed using properties of certain objects, variables, constants, 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

© 2001 by The McGraw-Hill Companies, Inc. All rights reserved Conversion Functions Functions perform an action and return a value Expression to operate on is called the Argument Conversion Functions convert arguments into a numeric value of the correct data type Conversion Functions on Text Boxes fail if user enters nonnumeric data or leaves the Text Box blank

© 2001 by The McGraw-Hill Companies, Inc. All rights reserved Conversion Functions (cont.) FunctionConvert To CInt **Integer CDecDecimal CStrString ** CInt rounds to the nearest Even Number

© 2001 by The McGraw-Hill Companies, Inc. All rights reserved Conversion Examples (also review examples p 96) Function Name Argument To Be Acted Upon intQuantity=CInt(txtQuantity.Text) decPrice=CDec(txtPrice.Text) intWholeNumber=CInt(decFractionalValue) decDollars=CDec(intDollars) strValue=CStr(decValue)

© 2001 by The McGraw-Hill Companies, Inc. All rights reserved Mathematical Operators OperatorOperation +Addition –Subtraction *Multiplication /Division \Integer Division ModModulus (division's remainder) ^Exponentiation

© 2001 by The McGraw-Hill Companies, Inc. All rights reserved Mathematical Order of Operations Computers solve math formulas based on a specific order 1st, then left to right 1. Parentheses 2. Exponentiation 3. Multiplication & Division 4. Integer Division 5. Modulus 6. Addition & Subtraction

© 2001 by The McGraw-Hill Companies, Inc. All rights reserved Mathematical Examples Note the use of parentheses to control 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

© 2001 by The McGraw-Hill Companies, Inc. All rights reserved Option Explicit On by default - should be left on If turned off –Variables can be used without first being declared –They will be defined by VB as data type Object To turn off –Code Option Explicit Off or Option Explicit in General Declarations –Set in Project Properties dialog box

© 2001 by The McGraw-Hill Companies, Inc. All rights reserved Option Strict Off by default - should be turned on If turned on –VB becomes strongly typed language –Will not allow implicit conversions from a wider data type to a narrower one or between String and numeric data types To turn on –Code Option Strict On in General Declarations –Set in Project Properties dialog box

© 2001 by The McGraw-Hill Companies, Inc. All rights reserved FormatCurrency Function General Form –FormatCurrency(NumericExpression) Returns a string of characters formatted as dollars and cents Includes a Dollar Sign, commas, and 2 decimal places by default Value returned is a String and can no longer be used in calculations

© 2001 by The McGraw-Hill Companies, Inc. All rights reserved FormatNumber Function General Form –FormatNumber(NumericExpression [, Decimal Places [, Leading Digit [, Use Parentheses for Negative Numbers [, Grouping for Digits] ] ] ] ) Formats with commas and specified number of decimal places (2 by default) Line Continuation not included on this slide

© 2001 by The McGraw-Hill Companies, Inc. All rights reserved FormatPercent Function General Form –FormatPercent(NumericExpression [, Decimal Places[, Leading Digit [, Use Parentheses for Negative Numbers [, Grouping for Digits ] ] ] ] ) Returns a string of characters formatted as a percent Multiplies the argument by 100, adds a percent sign and rounds to 2 decimal places by default Line Continuation not included on this slide

© 2001 by The McGraw-Hill Companies, Inc. All rights reserved FormatDateTime Function General Form –FormatDateTime(Expression [, Named Format] ) Expression can be: –String that holds a date or time –Date type variable

© 2001 by The McGraw-Hill Companies, Inc. All rights reserved Named Formats - FormatDateTime Function Named FormatExample DateFormat.GeneralDate2/28/99 6:01:24 PM DateFormat.ShortDate2/28/99 DateFormat.LongDateSunday, February 28, 1999 DateFormat.ShortTime18:01(24 Hour Clock) DateFormat.LongTime6:01:24 PM

© 2001 by The McGraw-Hill Companies, Inc. All rights reserved Handling Exceptions Exceptions occur when user enters unexpected/invalid data and program code does not anticipate this possibility, such as –User enters nonnumeric data in Text Box and code attempts to run a Numeric Conversion Function –User enters data that results in division by zero

© 2001 by The McGraw-Hill Companies, Inc. All rights reserved Try/Catch Blocks Used to catch and handle exceptions; referred to as error trapping or handling Enclose statements that might cause an error within Try/Catch Block –If an error occurs control is transferred to the Catch Block –Include a Finally statement to indicate code that should execute last whether or not an exception occurred

© 2001 by The McGraw-Hill Companies, Inc. All rights reserved 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 See p 111 for list of common Exception Classes

© 2001 by The McGraw-Hill Companies, Inc. All rights reserved Try Block - Example 1 Catches All Exceptions Try intQuantity=CInt(txtQuantity.Text) lblQuantity.Text=CStr(intQuantity) Catch lblMessage.Text="Error in input data." End Try

© 2001 by The McGraw-Hill Companies, Inc. All rights reserved Try Block - Example 2 Catches Specific Exception Try intQuantity=CInt(txtQuantity.Text) lblQuantity.Text=CStr(intQuantity) Catch MyErr as InvalidCastException lblMessage.Text="Error in input data." End Try Conversion exception, usually caused by nonnumeric or blank data

© 2001 by The McGraw-Hill Companies, Inc. All rights reserved Try Block - Example 3 Catches Multiple Specific Exceptions Try statements that may cause errors Catch MyErr as InvalidCastException error messages and statements for nonnumeric data Catch MyErr as ArithmeticException error messages and statements for calculation problems Catch MyErr as Exception error messages and statements for any other exception End Try

© 2001 by The McGraw-Hill Companies, Inc. All rights reserved MessageBox Object Use Show Method of MessageBox to display special type of window Arguments of Show method –Message to display –Optional Title Bar Caption –Optional Button(s) –Optional Icon

© 2001 by The McGraw-Hill Companies, Inc. All rights reserved MessageBox Syntax 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 –Arguments must be included to exactly match one of the predefined Signatures

© 2001 by The McGraw-Hill Companies, Inc. All rights reserved MessageBoxButtons Constants OK OKCancel RetryCancel YesNo YesNoCancel AbortRetryIgnore

© 2001 by The McGraw-Hill Companies, Inc. All rights reserved MessageBoxIcon Constants Asterisk Error Exclamation Hand Information None Question Stop Warning

© 2001 by The McGraw-Hill Companies, Inc. All rights reserved Counting & Accumulating Sums Must use Module/Form level variables since Local/Event level variables reset to 0 each time the procedure is called Summing –mdecOrderTotal = mdecOrderTotal + decItemPrice Counting –mintNumItems = mintNumItems + 1 –mintNumItems += mintNumItems Averaging –mdecAveSale = mdecOrderTotal / mintNumItems