410 likes | 432 Views
Chapter 3 Variables, Assignment Statements, and Arithmetic. Learning Objectives. Declare and use different types of variables in your project. Use text boxes for event-driven input and output. Use a four-step process to write code for event procedures
E N D
Learning Objectives • Declare and use different types of variables in your project. • Use text boxes for event-driven input and output. • Use a four-step process to write code for event procedures • Write Visual Basic instructions to carry out arithmetic operations. • Describe the hierarchy of operations for arithmetic. • Understand how to store the result of arithmetic operations in variables using assignment statements. • Use comments to explain the purpose of program statements. • Discuss using Visual Basic functions to carry out commonly used operations. • Use command buttons to clear text boxes, print a form with the PrintForm method, and exit the project. • Describe the types of errors that commonly occur in a Visual Basic project and their causes.
Variables • Variables are named locations in memory (memory cells) in which we store data that will change at run time • Variable names in VB:**** • Must begin with letter and can use 0-9 in name • Can’t include period, but can contain an underscore • Can’t be over 255 characters • Not case-sensitive, but suggest using upper and lower case • Example mnemonic variable names • sngProfit_Margin for Profit margin**** • curTaxes for taxes on this price • curAmountDue for sum of price and taxes • curYTDEarnings for year to date earnings
Data Types • Two primary types of data: numeric and string • Numeric data can be used in arithmetic operations • 3.154 2300 -34 .0000354 are all numeric constants • String data should not be used in arithmetic • “Dogs” “123-45-6789” “Dr. Brown” are all string constants • Numeric data types can be subdivided into specific types: • currency $55,567.78 integer 255 • single 567.78 long (integer) 35,455 • double 567.78129086 Boolean True or False**
Data Types (cont) • String - stores ASCII symbols (text) and numbers that are not used in mathematical operations, but rather to provide for the input, output, and manipulation of sets of characters • Integers - whole numbers (-32,768 to 32,767) • Long Integers - whole numbers (-2,147,483,648 to 2,147,483,647 • Single - fractional numbers to seven significant digits • Double - fractional numbers to 15 significant digits
Data Types (cont) • Currency - use with monetary amounts and up to four digits to the right of the decimal • Date - use with dates • Boolean - use only when the value of a variable is True or False • Variant - variable is assigned this type automatically if you don’t declare the variable as a specific data type, but takes up more memory
Advantages of Coding Prefixes • Standard allows anyone who reads the code to immediately determine data type of variable • Words that are normally reserved words can be used, i.e. strPrint • Different objects can practically same name, i.e lblAge (label), or txtAge (text box)
Declaring Variables • Declare ALL variables with the DIM statement **** • General form: • Dim Variable1 as type1, variable2 as type2, etc. • For example, • Dim strHerName as String, sngMyValue as Single • Dim curMyIncome as Currency, curPrice as Currency • Dim curAmountDue as Currency • Two or more variables can be declared with same Dim statement but you must include the variable type • If you fail to declare a variable after the Option Explicit statement has been entered, an error occurs at Run time • Use variables rather than objects in processing since all textboxes are strings
The Option Explicit Statement • Begin ALL Forms with the Option Explicit command in the declarations procedure of the general object. This forces all variables to be declared**** You may have to correct variable statements in your test! • To automatically include Option Explicit, go to the Tools|Options|Editor menu selection and check the box for “Require variable declaration”
Event-driven Input • In VB, we often use event-driven input where data is transferred from text boxes to variables by an event • **** The user, not the program controls the sequence of events • Use an assignment statement to do this:. : An assignment statement gives a variable a value by setting it equal either to an existing quantity or to a value that can be computed by the program Control property or variable = value, variable, or property • Only variables or controls can be on left of the = sign statement while the value, variable or property is on the right of the = sign
Comments • To explain the purpose of a statement, a comment statement is added • Any statement beginning with an apostrophe or REM is a comment • Comments can be added before statements or at the end of statements by using an apostrophe
VB Code Box 3-1Code to Input Two Numbers Private Sub cmdSum_Click ’Declare variables Dim intFirst as Integer, intSecond as Integer Dim intSum as Integer ’Assign values to variables intFirst = txtFirstNum.Text intSecond = txtSecondNum.Text End Sub
Functions • Function - an built -in operation that takes one or more more arguments and returns a a single value • A Common form of a function is variable=functionname(argument1, argument2 ….) • Not all functions require arguments such as the Date function • The VAL() function is very common and is used to convert the Text property from a string to a number, which is assigned to Numeric variable
Using Functions (cont) • You can’t use text boxes to do computations because the default property, Text, is a string and therefore must be converted to a numeric value before a calculation is performed. • It is necessary to convert the results of the computation that will appear in another text box to a string value , using the Str() function, otherwise you would be assigning an integer value to it • Example functions for converting data: • Val to convert a string to a number • Str to convert a number to a string
Assignment Statements • Must convert strings in text boxes to numeric with Val function, eg, • curPrice = Val(txtPrice) • Convert numeric variables to strings before assigning to text box, eg, • txtAmountDue = str(curAmountDue) • Carry out calculations with assignment statements, eg, • curTaxes = 0.07*Price • curAmountDue = curPrice + curTaxes
VB Code Box 3-2 Use Val() Function in Inputting Numbers Private Sub cmdSum_Click() ’Declare variables Dim intFirst as Integer,intSecond as Integer Dim intSum as Integer ’Assign values to variablesas number intFirst = Val(txtFirstNum.Text) intSecond = Val(txtSecondNum.Text) End Sub
VB Code Box 3-3Code for cmdSum Command Button Private Sub cmdSum_Click() ’Declare variables Dim intFirst as Integer, intSecond as Integer Dim intSum as Integer ’Assign values to variables as a number intFirst = Val(txtFirstNum.Text) intSecond = Val(txtSecondNum.Text) intSum = intFirst + intSecond ’Calculate sum txtSum.Text = Str(intSum) ’display sum in sum text box End Sub
Properties Versus Methods • The dot notation method is the way properties are set at run time. • Syntax: object. property= value E.g. txtSum.Text=Str(intSum) • The same notation is used to invoke a method for a control. Methods define the actions a control can carry out. • Syntax: object.method E.g. txtFirstNum.SetFocus • The SetFocus method shifts the cursor to the named text box • Methods can’t be used in assignment statements
VB Code Box 3-4Code for cmdClear Command Button Private Sub cmdClear_Click() ’Clear text boxes with empty string txtFirstNum.Text = "" txtSecondNum.Text = "" txtSum.Text = "" txtFirstNum.Setfocus ’Set focus back to first text box End Sub
Using Assignment Statements for Calculations • An expression is a combination of one or more variables and/or constants with operators • A constant is a quantity that does not change • Operators are symbols used for carrying out processing
Arithmetic Operators**** • () for grouping + for addition • ^ for exponentiation - for subtraction • - for negation * for multiplication • / for division • \ for integer division (divisor and dividend are rounded to 0) • Example 7.1111\1.95= 7\2 =3 • mod for modulus • Example 7.1111\1.95= 7\2 =3 with 1 remainder
Hierarchy of Operations**** • Operations within parentheses ( ) • Exponentiation (^) • Negation (-)' • Multiplication and division (*,/) • Integer division (\) • Modulo arithmetic (Mod) • Addition and subtraction (+,-) • String concatenation (&) • ****Make sure you know this!!!
Arithmetic Example • 3 * (Salary - Taxes)^2 + Bonus/Months 3 1 2 5 4 (order) • Order 1 Subtract Taxes from Salary 2 Square the result 3 Multiply this result by 3 4 Divide Bonus by Months 5 Subtract result from first expression ****You will see something like this again!
String Operators • For String Variables the only valid operation is that of combining two strings into one**** • Use + or & to combine them • Example: • strBigday = “Christmas” + “ Day” • strBigday = “Christmas” & “ Day” • Result of above is Christmas Day
Symbolic Constants • We can assign a name to a constant with the Const statement Syntax: Const constant name as variable type = value • Examples Const sngIntRate as Single = 0.07 Const intNumYears as Integer=12 Const sngIntRate as Single=0.07,intNumYears as Integer=12
Formatting Data • To display information in a pleasing form, we can use the Format function: • variable or control = Format(variable, “format expression”) • Where the format expressions are in quotes and include; • Currency • Fixed • Standard • Percent • Scientific • Example: txtTaxes.Text = Format(curTaxes, “currency”)
Print Form, Clearing Entries and Setting Focus • Create a command button called cmdPrint • To print the form, use the PrintForm command in the cmdPrint click event • _________________________________ • Create a command button called cmdClear • To clear a text boxes, set them equal to the null string “” • To set the focus to a text box, use the Setfocus method • For example, txtCustName.SetFocus sets focus to this textbox
Coding the Exit Button and Giving User Ability to Use Control Keys • Create Exit button called cmdExit • In the click event enter this line of code • END • User can also activate the click event from the keyboard by using the CTRL Key and underlined letter if the caption has an “&” before the applicable letter • Example E&xit for the Exit command button
Pseudocode to Compute and Output Taxes and Amount Due • Begin Procedure Calculate • Input customer name • Input video name • Input video price • Taxes = video price times tax rate • Amount due = video price + taxes • Output taxes • Output amount due • End procedure
VB Code Box 3-5Code for Calculate Button Private Sub cmdCalc_Click() ’Declare constant and variables Const sngTaxRate as Single = 0.07 ’Use local tax rate Dim curPrice As Currency, curAmountDue As Currency Dim curTaxes As Currency Price = CCur(TxtVideoPrice.Text) Taxes = Price * TaxRate ’calculate taxes AmountDue = Price + Taxes ’calculate amount due ’Display taxes and amount due in text boxes as strings txtTaxes.Text = Str(Taxes) txtAmountdue.Text = Str(AmountDue) End Sub
VB Code Box 3-6Code to Compute and Display Taxes and Amount Due Private Sub cmdCalc_Click() Const sngTaxRate as Single = 0.07 'Use local tax rate Dim curPrice As Currency, curAmountDue As Currency Dim curTaxes As Currency Price = CCur(txtVideoPrice.Text) Taxes = curPrice * sngTaxRate 'Compute taxes curAmountDue = curPrice + curTaxes 'Compute amount due 'Format text boxes as currency txtTaxes.Text = Format(curTaxes, "Currency") txtAmountDue.Text = Format(curAmountDue, "Currency") txtVideoPrice.Text = Format(curPrice, "Currency") End Sub
VB Code Box 3-7Code to Clear Entries in cmdClear Command Button Private Sub cmdClear_Click() ‘Clear all text boxes txtCustName.Text = "" txtVideoName.Text = "" txtVideoPrice.Text = "" txtTaxes.Text = "" txtAmountDue.Text = "" txtCustName.SetFocus ‘set focus to this text box End Sub
Using Other Arithmetic Functions • Other useful functions include • Abs for absolute value Sqr for square root • FV for future value PV for present value • IRR for internal rate of return Pmt for payment • UCase/LCase to convert to upper/lower case • Len for length of a string • Date for the system date • DateValue for the date corresponding to string argument • We will use Pmt to compute the monthly payment • MonPay = Pmt(rate, Nper,-LoanAmt) • Pmt(.08/12,60,-10000) = $256.03
Creating a Monthly Payment Calculator • Assume you wanted to determine the monthly payment necessary to pay off a loan at a given interest rate in some number of months • Use PMT function • PMT(rate, nper, pv) where • rate = monthly interest rate • nper = number of months • pv = negative value of loan amount
VB Code Box 3-8Code to Compute Monthly Payment Private Sub cmdCompute_Click() ‘Declare variables Dim curAmount As Currency, intMonths As Integer Dim sngRate As Single Dim curPayment As Currency ‘Convert variables in text boxes curAmount = CCur(txtAmount.Text) intMonths = CInt(txtMonths.Text) ‘Calculate monthly interest rate sngRate = (CSng(txtRate.Text) / 100) / 12 ‘Calculate payment curPayment = Pmt(sngRate, intMonths, -curAmount) txtPayment.Text = Format(curPayment, "Currency") txtAmount.Text = Format(curAmount, "Currency") End Sub
Visual Basic Errors • **** Most mistakes that happen while using VB are a result of human error - not hardware error • **** VB will NOT automatically detect and alert you to all errors!! • Syntax errors: caused by incorrect grammar, vocabulary, or spelling . Also caused by using a keyword. Usually caught as you enter the statement. These are pointed out by VB and are usually easy to find and correct.
Visual Basic Errors (con’t) • Run time errors: errors not caught at entry but which involve an incorrect statement or bad data, eg, dividing by zero. The presence of an error is detected by VB when you run the program, but you still have to find the source of the error. More difficult to correct than syntax errors • Logic errors: those that are VB does not catch as being “wrong”, but which involve erroneous logic, say, only having a program include 11 months of data instead of 12. These are the hardest to find! • Debuggingis the process of finding and correctingprogram errors. ****