400 likes | 547 Views
Variables. Variable – named memory location that stores value Names for variables: Must start with a letter May contain letters, numbers, underscore character May mix upper/lower case – VB is not case sensitive but will display names with case as stated in first usage
E N D
Variables • Variable – named memory location that stores value • Names for variables: • Must start with a letter • May contain letters, numbers, underscore character • May mix upper/lower case – VB is not case sensitive but will display names with case as stated in first usage • Max length of 255 characters (no spaces) • Declaring variables -> Dimension statement syntax: Dim variablename As datatype as: Dim intCounter As Integer Dim strMyName As String Visual Basic - Chapter 4
Pick out the invalid variable names: • X pi_to_45_digits • Y2K FebruaryDollars • y2K intValue • 2K 2005 • Next_Num Yr2005 • LAST-NUM Second Value • Revenue$ i Visual Basic - Chapter 4
Variables Worksheet Circle the invalid variable names: • j • LASTNAME • Dollar Amount • name_of_your_mother_in_law • intPi • Count-of-values • 2ndNum • CiRcUsNaMe • Monthly$Amt • %AvgIncrease Visual Basic - Chapter 4
Data Types and Naming Conventions Data TypePrefix • Single sgl single floating point • Double dbl double floating point • Integer int short integer (32,767 max) • Long lng long integer • Currency cur currency (with 4 decimals) • String str string text • Boolean bln Boolean (True/False) Visual Basic - Chapter 4
Dimension Statements • Place at the beginning of event procedure code (makes it easy to locate them) • Use prefixes and match to data types (makes it easy to tell what kind of variable anywhere in the code) • Automatically initialized in Visual Basic (but initialize anyway, since most languages do not do this) • Numeric variables to zero • String variables to empty string • Can declare multiple variables in single statement separating with commas Visual Basic - Chapter 4
Demo: Variables Display the results of dividing 4 by 3 in 4 different variable types: dblVar, intVar, curVar, and strVar. Private Sub Form_Load() Dim dblVar As Double Dim intVar As Integer Dim curVar As Currency Dim strVar As String dblVar = 4 / 3 intVar = 4 / 3 curVar = 4 / 3 strVar = "4 / 3" lblDouble.Caption = dblVar lblInteger.Caption = intVar lblCurrency.Caption = curVar lblString.Caption = strVar End Sub Visual Basic - Chapter 4
frmCalculations Calculations cmdDivide Divide 1.2 lblDivide Multiply Add Subtract Done cmdDone Exercise 3-8A: Calculations modified Modify Exercise 3-8 to use double variables for 6 and 5. Dim dblNum1 As Double Dim dblNum2 As Double dblNum1 = 6 dblNum2 = 5 lblDivide.Caption = dblNum1 / dblNum2 NEXT: Modify to use integer variables. Visual Basic - Chapter 4
Review 4-2: CircleArea modified Modify CircleArea to use variables to calculate and display area of a circle with radius of 6 when Calculate button is clicked. Private Sub cmdCalculate_Click() Dim dblRadius As Double Dim dblCircleArea As Double dblRadius = 6 dblCircleArea = 3.14 * dblRadius ^ 2 lblAnswer.Caption = dblCircleArea End Sub Visual Basic - Chapter 4
Syntax Errors • Visual Basic detects some syntax errors at design time, as, forgetting a value in an assignment statement Visual Basic - Chapter 4
Compile Errors • Visual Basic detects other errors, like misspellings, during compiling, as spelling dblRadius as dlbRadius: Visual Basic - Chapter 4
Run Time Errors • Visual Basic cannot detect some errors until the program executes, like an invalid value in a variable: • Click Debug to see which statement caused the problem Visual Basic - Chapter 4
Option Explicit • Assists in debugging programs by forcing declaration of variables • Appears in General section of form module (top of form module) • Can be manually typed in • Good practice to set as default for all new programs: Under Tools | Options, Editor tab, Check Require Variable Declaration item in Code Settings Comment out Option Explicit; change dblRadius = 6 to dlbRadius; rerun and see effect of not forcing variable declaration. Visual Basic - Chapter 4
Named Constants • Named memory location which stores a value that cannot be changed during program execution • Use to make code clear and easy to modify • Syntax: Const variablename As datatype = value • Examples: Const dblPI As Double = 3.14 Const intMax As Integer = 150 • Place BEFORE Dim statements • Don’t try to change value of constants in program Visual Basic - Chapter 4
Review 4-3: CircleArea modified Modify CircleArea to use a constant for value of Pi. Private Sub cmdCalculate_Click() Const dblPI As Double = 3.14 Dim dblRadius As Double Dim dblCircleArea As Double dblRadius = 6 dblCircleArea = dblPI * dblRadius ^ 2 lblAnswer.Caption = dblCircleArea End Sub NEXT: Change value of Pi constant to 3.14159 and see results. Visual Basic - Chapter 4
Immediate Window • Not always easy to find logic error “bugs” in an application • Displaying intermediate values in the Immediate window may help • To view Immediate window, select View | Immediate window • To close window, click X Close button in window Visual Basic - Chapter 4
Immediate window Docking Immediate Window • Drag Title bar to “dock” Immediate window • Suggest docking at left and resize to view Visual Basic - Chapter 4
Debug.Print • Insert Debug.Print statements in your code to display intermediate results • Syntax: Debug.Print followed by constants or variables separated by semicolons • Examples: Debug.Print “start”; dblRadius Debug.Print “intX ”; intX; “ intY ”; intY • Be sure to remove Debug.Print statements when done debugging code Visual Basic - Chapter 4
Review 4-6: CircleArea modified Insert Debug.Print statements in CircleArea. Visual Basic - Chapter 4
Create with TextBox control Use to obtain user input Common properties: Name: use txt prefix Text: text in the text box (type string) can be set by assignment automatically changes when user enters data [Change event procedure] Font: style, size of text Alignment: left/right/center text TextBox control Text Box Object Visual Basic - Chapter 4
Using Text Boxes • Text box has no caption property • Thus, common to precede each text box with a label that says what the text box contains • Text box does not use Click event; instead, Change event occurs when text contents change • BUT – usually do not process text with Change event (since it occurs with each change, not just when finished); instead, usually process in another object event • ALSO – Be sure to clear associated objects when starting new text box cycle. Visual Basic - Chapter 4
txtAnswer Review 4-7: CircleArea with text box Modify CircleArea to use text box to input radius of the circle. • Change cmdCalculate_Click() to set dblRadius from contents of text box: • dblRadius = txtAnswer.Text • Add txtRadius_Change() procedure (double-click text box) to clear label with prior calculations: • lblAnswer.Caption = “” Visual Basic - Chapter 4
converted to integer for use in calculations text box input is string data Automatic Type Conversion • In Assignment statements, Visual Basic tries to convert data to match type of variable assigned to • as, intLength = txtInputLength.Text • If the data is not valid for the receiving data type, a run-time error occurs for example, intX = “abc” would produce “Type mismatch” error Visual Basic - Chapter 4
numeric variable or value number of decimal places to round to Dim dblNumber As Double dblNumber = 3.457 lblAnswer.Caption = Round(dblNumber, 2) 3.46 Round Function • Used to round numeric data to a specified number of decimal places • Syntax: Round(number, decimal places) • Example: Visual Basic - Chapter 4
Rounding in Visual Basic • Visual Basic is used heavily for business applications involving adding columns of decimals • Rounding is performed in an unusual manner: • Decimal ending in digit > 5 is rounded up: 5.7 -> 6 • Decimal ending in digit < 5 is rounded down: 5.3 -> 5 • Decimal ending in digit 5: • If preceding digit is odd, rounds up: 5.5 -> 6 • If preceding digit is even, rounds down: 6.5 -> 6 Visual Basic - Chapter 4
numeric or string expression or variable IsNumeric Function • Run-time errors occur if non-numeric text box data is assigned to numeric variable, so... • Use IsNumeric function to test data beforehand • Syntax: IsNumeric(argument) Returns True if numeric, False if not [we’ll use as soon as we learn If statement] • Examples: lblAnswer.Caption = IsNumeric(“123”) ‘True lblAnswer.Caption = IsNumeric(“abc”) ‘False lblAnswer.Caption = IsNumeric(2 + 4) ‘True lblAnswer.Caption = IsNumeric(“2 + 4”) ‘False CircleArea: Click without entering a radius; enter “5e” as radius -> note run-time errors. Visual Basic - Chapter 4
Exercise 4-3: Rectangle modified Modify Rectangle to obtain length and width via text boxes. Be sure to add Change events to clear area and perimeter labels whenever text changes. Visual Basic - Chapter 4
Exercise 4-2: Temperature Conversion Calculate and display the Celsius equivalent of a Fahrenheit temperature the user enters. Conversion formula: Celsius = 5/9 of (Fahrenheit less 32) Test with values: 212 -> 100 32 -> 0 98.6 -> 37 -40 -> -40 Visual Basic - Chapter 4
What’s Wrong with This Statement? lblAnswer = txtLeng * txtWidth • Declare “dot property” declaration after every object: lblAnswer.Caption, txtLeng.Text, txtWidth.Text • Don’t do computations on strings; instead, test and store string “numbers” in numeric variables • Don’t do computing into a string (in this case, lblAnswer.Caption); instead, compute into numeric variable and then assign to string Dim dblLeng As Double, dblWidth As Double, dblArea As Double dblLeng = txtLeng.Text dblWidth = txtWidth.Text dblArea = dblLeng * dblWidth lblAnswer.Caption = dblArea Visual Basic - Chapter 4
3 • 27 • -21 • 6 \ Mod Integer Division • Two special operators in Visual Basic perform integer division: • \ returns the integer portion when dividing two integers, as, 27 \ 7 = 3 • Mod returns the remainder portion when dividing two integers, as, 27 Mod 7 = 6 Visual Basic - Chapter 3
Integer Division for Splitting Digits • Repeatedly divide by 10 to “cut” off right-most digit: 32 10 321 320 1 3 10 32 30 2 0 10 3 0 3 Dim intTemp As Integer Dim intDigit1 As Integer Dim intDigit2 As Integer Dim intDigit3 As Integer intTemp = 321 intDigit3 = intTemp Mod 10 intTemp = intTemp \ 10 intDigit2 = intTemp Mod 10 intTemp = intTemp \ 10 intDigit1 = intTemp Mod 10 Note: Divide by 60 to change minutes to hours and minutes Visual Basic - Chapter 4
Exercise 4-9: Digits of a Number Display the digits separately for a user-entered 2-digit number. Extra credit: Modify the application to work with 3-digit numbers. Visual Basic - Chapter 4
Create with OptionButton control Use to obtain user input by selecting one button from a set Common properties: Name: use opt or rad prefix Caption: text displayed with button Font: style, size of text Alignment: whether text left/right of button Value: whether button is selected (True is selected; False is not selected) OptionButton control Option [Radio] Button Object Visual Basic - Chapter 4
Using Option Button Sets • Use when the user may select only one out of a set of option buttons (like, size of pizza, color of bicycle) • Only 1 button can be selected at a time (when a new button is selected, former button automatically clears) • Always initialize one of the buttons during Form_Load by setting its .Value = True (then you don’t have to check that one is selected) • Click event occurs when a button is selected • Group buttons within a Frame object (otherwise all buttons belong to one set on the form) Visual Basic - Chapter 4
Create with Frame control Use as a container for grouping other objects, like option buttons Common properties: Name: use fra prefix Caption: text displayed at top of frame box Frame control Frame Object Visual Basic - Chapter 4
Creating Button Groups • Double-click Frame control • Name/caption the frame and resize/position it • Drag option buttons into the frame using the OptionButton control. [Note: DO NOT double-click on option buttons; that makes them part of the form group, not a frame group (even if you then drag them into a frame)] • Position buttons within the frame • All buttons will move together with the frame (good way to tell if the buttons are part of the frame group) Visual Basic - Chapter 4
Review 4-11: HelloWorld International Allow the user to see greeting in English (“Hello, world!”), Spanish (“Hola mundo!”), or French (“Bonjour le monde!”). Set lblMessage Caption to appropriate text in each of the optLanguage_Click() events Be sure to include a Form_Load event that initializes optEnglish.Value to True and lblMessage Caption to English. Visual Basic - Chapter 4
Programming Style Guidelines • Liberal and descriptive comments • Descriptive names with appropriate prefixes • Dot properties on all object references • Constants for unchanging values, declared at very beginning of procedures • Appropriate variable types, declared at beginning of procedures • Properly indented statements • Option Explicit statement to detect misspelled names • No computations on or into strings Visual Basic - Chapter 4
Application Development Process • Specification: defining clearly what the application should accomplish • Design: describing how the user interface will look and how the program code will be written to accomplish the goals of the specification • Coding: creating the interface and writing the code • Testing: testing the code with varieties of test data and scenarios • Debugging: Fixing problems (and then retesting) Visual Basic - Chapter 4
Exercise 4-10: Hello Good-bye with option buttons Modify Exercise 3-7 to display “Hello!” or “Good-bye”, depending on which option button is clicked. Don’t forget to initialize to Hello! in Form_Load. Visual Basic - Chapter 4