Variables and Constants Variable Memory locations that hold data that can be changed during project execution Example: a customer’s name Constant Memory.

Slides:



Advertisements
Similar presentations
1.
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.
Objectives Understand the software development lifecycle Perform calculations Use decision structures Perform data validation Use logical operators Use.
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
IS437: Fall 2004 Instructor: Dr. Boris Jukic Data Types, Constants, Variables, Scope, Conversion.
Chapter 3: Introducing the Microsoft.NET Framework and Visual Basic.NET Visual Basic.NET Programming: From Problem Analysis to Program Design.
Basic Elements of C++ Chapter 2.
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.
T U T O R I A L  2009 Pearson Education, Inc. All rights reserved. 1 6 Enhancing the Inventory Application Introducing Variables, Memory Concepts and.
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
CS0004: Introduction to Programming Variables – Numbers.
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?
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.
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.
Introduction to Visual Basic Programming. Introduction Simple Program: Printing a Line of Text Another Simple Program: Adding Integers Memory Concepts.
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.
Programming with Microsoft Visual Basic 2008 Fourth Edition Chapter Three Using Variables and Constants.
Exceptions, handling exceptions & message boxes Year 11 Information Technology.
Data Tonga Institute of Higher Education. Variables Programs need to remember values.  Example: A program that keeps track of sales needs to remember.
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
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.
Microsoft Visual Basic 2012 CHAPTER FOUR Variables and Arithmetic Operations.
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.
Programming with Microsoft Visual Basic 2012 Chapter 3: Using Variables and Constants.
© 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.
A variable is a name for a value stored in memory.
Chapter 2 Variables.
Chapter 3: Variables, Constants, and Calculations
Arithmetic operations and operators, converting data types and formatting programs for output. Year 11 Information Technology.
Variables and Arithmetic Operations
Variables and Arithmetic Operations
Visual Basic Programming Chapter Four Notes Working with Variables, Constants, Data Types, and Expressions GROUPBOX CONTROL The _____________________________________.
Chapter 2 Variables.
Brief description on how to navigate within this presentation (ppt)
Introduction to Visual Basic
Chapter 2 Variables.
Brief description on how to navigate within this presentation (ppt)
Presentation transcript:

Variables and Constants Variable Memory locations that hold data that can be changed during project execution Example: a customer’s name Constant Memory locations that hold data that cannot be changed during project execution Example: the sales tax rate In VB, use a Declaration statement to establish variables and constants

3- All Variables & Constants Have a Data Type 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

Naming Variables and Constants Follow Visual Basic naming rules: – must begin with a letter – letters, digits, and underscores only (no spaces, periods) – no reserved words such as Print or Class Follow naming conventions such as: use meaningful names, e.g. taxRate, not x include the data type in the name, e.g., countInteger use mixed case for variables and uppercase for constants quantityInteger or HOURLYRATEDecimal

Declaring Variables Inside of a procedure: Dim customerName As String Outside of a procedure: Public totalCost As Decimal Private numItems As Integer Ok to declare several variables at once: Dim numMales, numFemales as Integer

Declaring Constants Intrinsic Constants: built-in and ready to use: Color.Red is predefined in Visual Basic Named Constants Use Const keyword to declare Append a type declaration after the value: D=decimal, R=double, F=single, I=integer, L=long, S=short Const SALES_TAX_RATE As Decimal =.07D Const NUM_STUDENTS As Integer = 100I Const COMPANY_ADDRESS As String = "101 Main Street"

Scope of a Variable Scope of a variable means the how long the variable exists and can be used The scope may be: Namespace – available to all procedures of a project; also called a global variable Module level – available to all procedures in a module (usually a form) Local – available to only the procedure where it’s declared Block level – available only within the block of code where it’s declared

3- Arithmetic Operations OperatorOperation Order () Group operations 1 ^Exponentiation 2 * /Multiplication/ Division 3 \Integer Division 4 ModModulus – Remainder of division Addition/ Subtraction 6 “Please Excuse My Dear Aunt Sally” 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

Performing Arithmetic Operations in Visual Basic Calculations can be performed with variables and constants that contain numeric data Calculations cannot be performed on string data Remember: values from Text property of Text Boxes are strings, even if they contain numeric data. So … – String data must be converted to a numeric data type before performing a calculation – Numeric data must be converted back to strings before insertion into a text box.

Example Weight in Pounds: 5 Weight in Ounces: 80 Dim lbs, ozs As Integer lbs = Integer.Parse(poundsTextBox.Text) ozs = lbs*16 ouncesTextBox.Text = ozs.ToString() Parse() method fails if user enters nonnumeric data or leaves data blank.

Assignment Statement in Visual Basic Form: variable = arithmetic operation Write This: area = * radius ^ 2 Not This: * radius ^ 2 = area Shorthand Assignment: You can write This: sum = sum + grade Like This: sum += grade Other shorthand assignments: +=, -=, *=, /=, \=, &=

3- Converting Between Numeric Data Types Implicit conversion Converts value from narrower data type to wider Example: Dim littleNum As Short Dim bigNum As Long bigNum = littleNum Explicit conversion (casting) Uses methods of Convert class to convert between data types Example: Dim littleNum As Short Dim bigNum As Long bigNum = Convert.ToInt64(littleNum)

Two Important Project Options in Visual Basic Option Explicit :variables must be declared before using. (Should always be on.) Option Strict: does not allow implicit conversions Makes VB a strongly typed language like C++, Java and C# Recommended to be turned on in the Project Properties menu.

Formatting String Data for Display To display numeric data in a label or text box, first convert value to string using the ToString() method Add a formatting code to display things like: dollar signs, percent signs, and commas a specific number of digits that appear to right of decimal point a date in a specific format Example: Dim total As Decimal Dim stringTotal As String total = stringTotal = total.ToString(“C”) sets stringTotal to “$1,234.57”

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

Date Specifier Code Examples Dim dt As Date Dim dtString As String dtString = dt.ToString(“d”)

Handling Exceptions Exceptions - run-time errors that occur Error trapping - catching exceptions Error handling – writing code to deal with the exception The process is standardized in Visual Studio using try/ catch blocks. – put code that might cause an exception in a Try block – put code that handles the exception in a Catch block

3- Try/ Catch Blocks Try ‘statements that may cause an error Catch [VariableName As ExceptionType] ‘statements that handle the error [Finally ‘statements that always run in the Try block] End Try Try Quantity = Integer.Parse(QuantityTextBox.Text) QuantityTextBox.Text = Quantity.ToString() Catch MessageLabel.Text = "Error in input data." End Try

3- Try/Catch Block — Multiple Exceptions Try Score = Integer.Parse(scoreTextBox.Text) Total += Score Average = Total/ NumStudents MessageLabel.Text = Average.ToString() Catch TheException As FormatException MessageLabel.Text = "Error in input data.” Catch TheException As ArithmeticException MessageLabel.Text = "Error in calculation.” Catch TheException As Exception MessageLabel.Text = “General Error.” Finally NumStudents += 1 End Try

MessageBox Object The MessageBox object is a popup window that displays information with various icons and buttons included. MessageBox.Show() is the method for displaying the message box. There are 21 different variations of the argument list to choose from (different combinations of parameters) IntelliSense displays argument lists, making the task of choosing the right one easier

MessageBox.Show() Message – text to display in the box Title – text to display in the title bar Buttons – the set of buttons to include in the box OK, OKCancel, RetryCancel, YesNo, YesNoCancel, AbortRetryIgnore Icons – the icon to display in the box Asterisk, Error, Exclamation, Hand, Information, None, Question, Stop, Warning MessageBox.Show(Message, Title, Buttons, Icon)

Overloaded Methods MessageBox.Show() is an example of an overloaded method. Overloaded methods have more than one argument list that can be used to call the method. Each different argument list is called a signature. Supplied arguments must exactly match one of the signatures provided by the method (i.e. same number of arguments, same type of arguments, same order of the arguments). IntelliSense in Visual Studio editor helps when entering arguments so that they don’t need to be memorized.

A Complete Example (Exercise 3.1, p. 149) Create a form that lets the user enter for a food: grams of fat, grams of carbohydrates, & grams of protein When the user presses the Calculate button, to following is displayed: 1. total calories for that food (1 gram of fat = 9 calories, 1 gram of carbs or protein = 4 calories), 2. total number of food entered so far 3. total calories of all the foods Also add buttons for Clear, Print and Exit. Catch any bad input data and display an appropriate message box.