570 likes | 1.95k Views
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
E N D
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
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
Arithmetic Operations • Operator Operation Order • () Group operations 1 • ^ Exponentiation 2 • * / Multiplication/ Division 3 • \ Integer Division 4 • Mod Modulus – Remainder of division 5 • + - Addition/ Subtraction 6 “Please Excuse My Dear Aunt Sally” 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
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 = 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: +=, -=, *=, /=, \=, &=
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 = 1234.5678 stringTotal = total.ToString(“C”) sets stringTotal to “$1,234.57”
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
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
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() MessageBox.Show(Message, Title, Buttons, Icon) • 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
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.