Presentation is loading. Please wait.

Presentation is loading. Please wait.

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

Similar presentations


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

1 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

2 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

3 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

4 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

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

6 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

7 3- Arithmetic Operations OperatorOperation Order () Group operations 1 ^Exponentiation 2 * /Multiplication/ Division 3 \Integer Division 4 ModModulus – Remainder of division 5 + - 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

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

9 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.

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

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

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

13 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 = 1234.5678 stringTotal = total.ToString(“C”) sets stringTotal to “$1,234.57”

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

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

16 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

17 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

18 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

19 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

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

21 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.

22 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.


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

Similar presentations


Ads by Google