1 / 22

Variables and Constants

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

Download Presentation

Variables and Constants

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

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

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

  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. 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. Format Specifier Code Examples

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

  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.

More Related