COPYRIGHT 2010 Dr David Scanlan CSUS Variables Constants
COPYRIGHT 2010: Dr. David Scanlan, CSUS Variables, Constants and Calculations • Conventions for Naming VB. NET Objects. • The meaning of Variable and Constant names. • VB. NET data types. (Types of Data) • Naming rules and conventions for variables and constants. • Declaring Variables and Constants. • Scope of Variables. • Lifetime of Variables • Format functions • Date/Time functions • Try/Catch
COPYRIGHT 2010: Dr. David Scanlan, CSUS Conventions for Naming VB. NET Objects
COPYRIGHT 2010: Dr. David Scanlan, CSUS Conventions for Naming VB. NET Objects Object Class Form Button Text. Box Label Radio button Check. Box Horizontal scroll bar Vertical scroll bar Picture. Box Combo. Box List. Box Prefix frm btn txt lbl rad chk hsb vsb pic cbo lst Ch 1 Example frm. Payroll btn. Exit txt. Last. Name lbl. Report. Heading rad. Interest. Rate chk. Landscape hsb. Spreadsheet vsb. Spreadsheet pic. Company. Logo cbo. Student. List lst. Courses The prefixes that are colored above are most likely to be used in this course.
COPYRIGHT 2010: Dr. David Scanlan, CSUS Naming physical locations in memory: Variables and Constants
COPYRIGHT 2010: Dr. David Scanlan, CSUS Variables and Constants Ch 3 Variable • A variable is a NAME that is used to reference the actual physical location (address) of a value in memory. • For example: dec. Daily. Total. Sales could be used to hold the total (2300. 27) for a shoe store's daily sales. dec. Daily. Total. Sales would be much easier to work with than an actual physical location, such as: 10101111011. • The value of this type of location can change during program execution. 2300. 27 Memory module Location of value: dec. Daily. Total. Sales or 10101111011
COPYRIGHT 2010: Dr. David Scanlan, CSUS Variables and Constants Ch 3 Constant • A constant is a NAME that is used to reference the actual physical location (address) of a value in memory. • For example: The name dec. SALES_TAX_RATE could be used to hold the sales tax (. 0784) for a shoe store. dec. SALES_TAX_RATE would be much easier to work with than the actual physical location: 1110101011110111001. • The value of this type of location cannot change during program execution. . 0784 Memory module Location of value: dec. SALES_TAX_RATE or 1110101011110111001
COPYRIGHT 2010: Dr. David Scanlan, CSUS Variables and Constants Using a name rather than the actual physical address. • It is a lot easier to use a name for a location than the actual physical address. • Example: Let's say there is a party at Mary's house. We could use "Mary's house" instead of the physical address "1274 South Main Street, Smalltown, CA" That's correct the party is at Mary's house. Smalltown, CA Mary's house 1274 South Main Street Ch 3
COPYRIGHT 2010: Dr. David Scanlan, CSUS Data Types The types of data you can store in memory as variables and constants
COPYRIGHT 2010: Dr. David Scanlan, CSUS Data Types Ch 3 Data Types (Types of Data is another way to express this concept. ) • When we use variables and constants in a program we must tell the program what type of data we are going to be storing in our memory locations: • dec. SALES_TAX_RATE: Decimal • str. Customers. Name: String • dec. Daily. Total. Sales: Decimal • shr. Daily. Shoes. Sold: Short Data Type Boolean Byte Char Date Decimal Single Double Short Integer Long String Use for: True or False values 0 to 255, binary data Single Unicode character (65, 536 characters) 1/1/0001 through 12/31/9999 Decimal fractions such as dollars and cents +/- 79, 228, 162, 514, 264, 337, 593, 543, 950, 335 (with 28 places to the right of the decimal point. ) Single-precision floating point: 6 digit accuracy Double-precision floating point: 14 digit accuracy Small size integer: -32, 768 to 32, 767 Medium size integer: -2, 147, 483, 648 to 2, 147, 483, 647 Large size integer: -9, 223, 372, 036, 854, 775, 808 to 9, 223, 372, 036, 854, 775, 807 Letter, digits, (characters on a typical keyboard) (0 to 2 Billion Unicode characters if you have enough memory. ) Bytes 2 1 2 8 16 4 8 2 4 8 Varies
COPYRIGHT 2010: Dr. David Scanlan, CSUS Data Types Ch 3 IMPORTANT For business calculations ALWAYS use the Decimal type of data. • This type of Data storage is accurate. For business calculations NEVER use Single or Double types of Data. Why? Single and Double numbers are stored in scientific notation. Single and Double numbers produce inaccuracies. These should be used in science for very large or very small number. Examples 1. 456 X 10 -85 or 1. 456 X 10+128 Your author (Gaddis) uses Single and Double in business calculations. THIS IS BAD PRACTICE. For this class, ALWAYS use the Decimal data type for any value that has a fractional part, such as 7. 99. Use Short, Integer, and Long for Whole numbers.
COPYRIGHT 2010: Dr. David Scanlan, CSUS Data Types Ch 3 Double Data Type vs Decimal Data Type X = 2. 11 R - 2. 1 R vs X = 2. 11 D - 2. 1 D GUI Before Running The Code GUI After Running The Code
COPYRIGHT 2010: Dr. David Scanlan, CSUS Rules & Conventions for Naming Variables and Constants
COPYRIGHT 2010: Dr. David Scanlan, CSUS Naming Rules & Conventions Naming Conventions: Variables and Constants • Use three-letter lower case prefixes to indicate the data type. bln Boolean dat Date dec Decimal Very important dbl Double-precision floating point shr Short Integer int Integer lng Long integer sng Single-precision floating point str String • User-defined names must be as meaningful as possible and as short as possible or as long as necessary. Concentrate on short and meaningful. • It is very important that you think long and hard about the best possible name. • dec. SALES_TAX_RATE not dec. TAX_RATE NOTE: dec. TAX_RATE is ok if the rate could only be sales tax and not income tax, etc. • dec. SALES_TAX_RATE not dec. TAX • str. SSN or str. Social. Security. Number not str. Federal. Social. Security. Num Ch 3
COPYRIGHT 2010: Dr. David Scanlan, CSUS Naming Rules & Conventions Ch 3 Naming Conventions: Variables and Constants • Constants: all upper case. • lng. SPEED_OF_LIGHT • Variables: Mix upper and lower case. • dec. Hours. Worked • dec. Pay. Rate Naming Rules: Variable and Constants • Letters, digits, and underscore, only. • Begin with a letter. • No spaces or periods • No reserved words (keywords) • Reserved words can be imbedded in the variable or constant name. Example int. Dim. Light. Value is ok even though it has a reserved word in it; that is, "Dim" • Maximum length: 16, 383 characters • Variable and constant names are collectively called IDENTIFIERS. • When we use a name for a physical location in memory, we call this name an IDENTIFIER.
COPYRIGHT 2010: Dr. David Scanlan, CSUS Naming Rules & Conventions Why are these correct or incorrect? • str. Pay. Rate • bln. Social. Securtiy. Number • int. Number. sold • Text • IF • DO • int. Daily. Sales • lng. Total. Bedrooms • dbl. Gross. Pay • sng. Gross. Pay • dec. Gross. Pay • str. Social. Security. Number • str. Last. Name • str. Company. Name • dec. Pay. Rate or dec. Hourly. Pay. Rate • int. Quanty. In. Stock • str. Item. Description INCORRECT Ch 3
COPYRIGHT 2010: Dr. David Scanlan, CSUS Declaring Variables and Constants
COPYRIGHT 2010: Dr. David Scanlan, CSUS Declaring Variables and Constants Ch 3 Declaring Variables and Constants: • IMPORTANT: When you declare a variable or constant, you are telling the program to reserve a physical location for this variable or constant in memory and to format that location so that it can hold a certain type of data, such as decimal, string, integer, etc. You are also giving the location a name (an identifier) to be used to access its physical location. Declaring Variables • General Form • Dim Identifier As Datatype [= Inital. Value] • Examples: • Dim str. Last. Name as String • Dim dec. Gross. Pay as Decimal • Dim dec. Total. Auto. Sales as Decimal • Dim dec. Legal. Fees as Decimal • Dim int. Tire. Units. Sold as Integer • Dim shr. Hours. Worked as Short • Dim shr. Employee. Age as Short • Dim str. Company. Name as String = "Ford" • Dim shr. Loan. Term as Short = 30 NOTE: Dim is short for Dimension the number of bytes in the location. The location value can be changed during runtime. Result of a Dim Statement: Dim dec. Gross. Pay as Decimal • Uses dec. Gross. Pay instead of an actual physical address in memory. • Reserves 16 bytes in memory and formats it so that fractional values can be stored. Memory Module
COPYRIGHT 2010: Dr. David Scanlan, CSUS Declaring Variables and Constants Ch 3 Declaring Variables and Constants: • IMPORTANT: When you declare a variable or constant, you are telling the program to reserve a physical location for this variable or constant in memory and to format that location so that it can hold a certain type of data, such as decimal, string, integer, etc. You are also giving the location a name (an identifier) to be used to access its physical location. PROBLEM: "I" not needed and hard to read. Makes 100 Declaring "Named" Constants: look like 1001. • General Form 100 is automatically stored as • Const IDENTIFIER As Datatype = Value an integer because it has no • Examples: fractional parts. • Const str. COMPANY_NAME as String = "Ace" • Const dec. SALES_TAX_RATE as Decimal = 0. 078 D • Const dec. MAXIMUM_PAY as Decimal = 2000. 00 D Result of Const Statement: Const dec. SALES_TAX_RATE as Decimal = 0. 078 D • Const dec. MAXIMUM_HOURS as Decimal = 50 D • Use dec. SALES_TAX_RATE instead of actual physical address in memory. • Const int. CENTURY as Integer = 100 I • Reserves 16 bytes in memory and formats it so that decimal values can be used. NOTE: Const is short for Constant. The value in a Constant location cannot change during runtime. "Named" constants are defined by the programmer using the "Const" keyword. Memory Module
COPYRIGHT 2010: Dr. David Scanlan, CSUS Assigning Values to Constants
COPYRIGHT 2010: Dr. David Scanlan, CSUS Assigning Values to Constants Rules for assigning values to constants: • • Text (Strings) must be enclosed in quotation marks. • Const str. COMPANY_BUSINESS_ID as String = "1254 -234" Numeric values used in computations are not enclosed in quotation marks. • Const dec. MAXIMUM_OVERTIME as decimal = 15 D • More rules for numeric constants: Important to remember: • 0 -9 If you don't use the "D", 1000. 95 will • decimal point be automatically stored in scientific • + or - on left side only notation (Double) format. • No commas, dollar sign, etc. • Type declaration characters: • Decimal D 1000. 95 D • Double R 5436. 65 R • Integer I 60344 I Numeric Literals • Long L 32323987766323 L • Short S 273 S • Single F 638874. 788 F • If you do not use type declarations (Defaults) • Whole numbers default to Integer. • Numbers with decimal points default to Double. Literals: 1. String values enclosed in quotes. (String literals) 2. Numbers such as those above: 1000. 95 D, 5436. 65 R, etc. (Numeric literals) Ch 3
COPYRIGHT 2010: Dr. David Scanlan, CSUS Scope of Variables
COPYRIGHT 2010: Dr. David Scanlan, CSUS Scope Variables Ch 3 Scope of Variables: • Scope refers to the parts of the program that are allowed to use the variable. • A good programmer tries to restrict variable access to only the part/s of the program that need the access. This is similar to the "Need to know. . . " philosophy of the military. • Keep scope to a minimum. • Why? If a variable, such as, int. Counter can be used anywhere in a million line program, it is very possible that its use in one part of the program will interfere with its use in another part. You will be told only what you need to know to accomplish your mission.
COPYRIGHT 2010: Dr. David Scanlan, CSUS Scope Variables Fig-3_0000 The following two programs demonstrate the Scope of Module-level and Local-level Variables. Module-level variables: Variables declared at this level can be used in any sub procedure in Form 1. Local-level variables: These variables are called "local variables" and are only usable within the sub procedure in which they are declared. If you try to use them outside this sub procedure, a compile-time error will result. Your author (Gaddis) uses the term class-level variable which has exactly the same meaning as the term module-level variable. Microsoft uses the term module-level Variable. Dr. Scanlan follows Microsoft's standard and so do his course notes.
COPYRIGHT 2010: Dr. David Scanlan, CSUS Start of In-Class Program Chapter 3: Scope of Local Variables Directions: 1. Create the GUI on the right. 2. Insert the code below into the two button click event procedures. 3. Button 1 event will function properly. 4. Button 2 event will produce an error. Why? Answer: The variable txt. Company. Name was declared in Button 1's procedure and is not recognized outside of the procedure in which it was declared. Thus, the variable txt. Company. Name is LOCAL to Button 1. Local Variable Not recognized End of In-Class Program
COPYRIGHT 2010: Dr. David Scanlan, CSUS Scope Variables Fig-3_0000 Local Variables Local-level variables: These variables are called "local variables" and are only usable within the sub procedure in which they are declared. If you try to use them outside this sub procedure, a syntax error will result. Pressing Button 1 will display "Ace Computers". Button 2 procedure has an error; thus, this procedure will not work. See next slide for details.
COPYRIGHT 2010: Dr. David Scanlan, CSUS Scope Variables Fig-3_0000 Local Variables Local-level variables: These variables are called "local variables" and are only usable within the sub procedure in which they are declared. If you try to use them outside this sub procedure, a syntax error will result. This variable is LOCAL to the Button 1 procedure and is recognized and usable within the Button 1 procedure, because it is declared within the Button 1 procedure. This same variable name is not recognize or usable outside the Button 1 procedure. Attempting to use it in another procedure will cause an error. Note the squiggly line indicating an error.
COPYRIGHT 2010: Dr. David Scanlan, CSUS Start of In-Class Program Chapter 3: Scope of Module-Level Variables Declaration Section Directions: 1. Create the GUI on the right. 2. Insert the code below into the two, button click event procedures. 3. Button 1 event will function properly. 4. Button 2 event will function properly. Why? Answer: mtxt. Company. Name was declared in the declaration section. This makes the variable known to ALL procedures in the form. mtxt. Company. Name is said to be at the "module-Level" and is usable by all procedures. Module-Level Variable Recognized End of In-Class Program
Scope Variables COPYRIGHT 2010: Dr. David Scanlan, CSUS Module-Level Variables Module-level variables: These variables are called "module-level variables" and are usable within ANY sub procedure in the Form in which they are declared. Thus, a module-level variable declared within Form 1 can be used in any sub procedure within Form 1. Pressing Button 1 will display "Ace Computers". Pressing Button 2 will display "Ace Computers". Fig-3_0000
COPYRIGHT 2010: Dr. David Scanlan, CSUS Scope Variables Module-Level Variables Module-level variables: These variables are called "module-level variables" and are usable within ANY sub procedure in the form in which they are declared. Thus, a module-level variable declared within Form 1 can be used in any sub procedure within Form 1. This variable (mtxtcompanyname) is module-level and is recognized and usable within ANY procedure within Form 1. A module level variable MUST be declared within the Declaration Section. See below. The "m" indicates to the reader that the variable is module-level. Use it in this course. Declaration section Fig-3_0000
COPYRIGHT 2010: Dr. David Scanlan, CSUS Scope of Variables I'm a "Modulelevel Variable" from Texas and everybody knows my name inside the Form called Texas. I'm a "Local Variable" from Roundville, TX and nobody knows my name outside of Roundville. I'm a "Local Variable" from Squareville, TX and nobody knows my name outside of Squareville. Governor I'm a "Local Variable" from Ovalville, TX and nobody knows my name outside of Ovalville. My name is Texas and I am a Form. They call me "frm. Lone. Star".
COPYRIGHT 2010: Dr. David Scanlan, CSUS Scope of Variables Private Sub Procedure(. . . ) • Variables declared within this SUB Procedure are only useable within this colored area. This Procedure can use any Module-level variable. • This colored area may use any Module-level Variable. • Dim txt. Local. Variable as String Local variables • Dim int. Counter as integer End Sub End Class Same names but different locations in memory. Public Class Form 1 Module-level Variables • Variables declared at the Module-level are usable anywhere within this yellow Form. This includes the blue and green colored areas, too. • Dim mtxt. Module. Level. Variable as String Module-level variables • Dim mdec. Module. Level. Variable as Decimal
COPYRIGHT 2010: Dr. David Scanlan, CSUS Lifetime of Variables Local Variables Module-level Variables
File: Ch 3 In. Class. ProjectsLifetime. Local. Variables. ppt COPYRIGHT 2010: Dr. David Scanlan, CSUS Start of In-Class Program Chapter 3: Lifetime of Local Variables Directions: 1. Create the GUI on the right. 2. Press the button twice and use the code below. 3. Note: Pressing the button over and over does not increment Total. Why? int. Total is a local variable: 1. It is reset to zero each time the button is pressed; thus it will never increment beyond the value of one. Additional information: Local variables are only "known" within the procedure in which they are declared. End of In-Class Program
COPYRIGHT 2010: Dr. David Scanlan, CSUS Lifetime of Variables Fig-3_0000 The following two programs demonstrate the lifetime of Module-level and Local-level Variables. Local-level variables: 1. Local variables are initialized to zero each time their sub procedure in which they were declared is called. Thus, numeric variables get initialized to zero and string variables get set to null. The Total will never get higher than 1. Pressing this button repeatedly should increase Total by 1 each time it is pressed. int. Total = int. Total + 1
COPYRIGHT 2010: Dr. David Scanlan, CSUS Lifetime of Variables Fig-3_0000 This program demonstrates the lifetime of a Local-level Variable. Local-level variables: 1. Local variables are initialized to zero each time their sub procedure in which they were declared is called. Thus, numeric variables get initialized to zero and string variables get set to null. This local variable (int. Total) gets reset to zero each time Button 1 is clicked. In other words, the statement "Dim int. Total as Integer" will get executed each time Button 1 is clicked, and int. Total will get reset to 0 each time. Can never accumulate beyond one.
File: Ch 3 In. Class. ProjectsLifetime. Local. Variables. ppt COPYRIGHT 2010: Dr. David Scanlan, CSUS Start of In-Class Program Chapter 3: Lifetime of Module Level Variables Directions: 1. Create the GUI on the right. 2. Place the code below into Form 1. 3. Note: Pressing the button over and over does increment the Total. Why? mint. Total is a module level variable: 1. It is NOT reset to zero each time the button is pressed; It keeps it last assigned value until the program is stopped. 2. It is only reset to zero when the program is started. When a variable is declared in the Declaration section, it is ALWAYS a module-level variable. Additional information: Module level variables are "known" within any procedure within the form. End of In-Class Program
COPYRIGHT 2010: Dr. David Scanlan, CSUS Lifetime of Variables Fig-3_0000 This program demonstrates the lifetime of Module-level and Local-level Variables. Module-level variables: 1. Module-level variables are initialized when the program first starts, and keep their last assigned value UNTIL the program is STOPPED. Button 1 was pressed 21 times. Note that the Total displayed is 21. One was added to Total each time the Button 1 was pressed.
COPYRIGHT 2010: Dr. David Scanlan, CSUS Lifetime of Variables Fig-3_0000 This program demonstrates the lifetime of Module-level and Local-level Variables. Module-level variables: 1. Module-level variables are initialized when the program first starts, and keep their last assigned value UNTIL the program is STOPPED. This module-level variable (mint. Total) does not get reset to zero each time Button 1 is clicked. In other words, the statement "Dim mint. Total as Integer" will not get executed each time Button 1 is clicked. The statement only gets executed when the program is first started, and that is when it gets created and initialized to zero. Declaration Section Module-level variables are ALWAYS declared in the Declaration Section.
COPYRIGHT 2010: Dr. David Scanlan, CSUS Lifetime of Variables Fig-3_0000 This program demonstrates the lifetime of Module-level and Local-level Variables. Module-level variables: 1. Module-level variables are initialized when the program first starts, and keep their last assigned value UNTIL the program is STOPPED. This module-level variable (mint. Total) does not get reset to zero each time Button 1 is clicked. In other words, the statement "Dim mint. Total as Integer" will not get executed each time Button 1 is clicked. The statement only gets executed when the program is first started, and that is when it gets created and initialized to zero. Declaration Section Module-level variables are ALWAYS declared in the Declaration Section.
COPYRIGHT 2010: Dr. David Scanlan, CSUS Lifetime of Variables (Static) Fig-3_0000 This program demonstrates the lifetime of a Local-level Variable using a Static declaration Local-level variables using a STATIC declaration: 1. If you use Static instead of Dim in the local variable declaration, the variable is NOT reset to zero each time the procedure is run. lation u m u r acc o f w ill allo !!! w ! e l t b varia ea a f r o ration pressed. sg a l i c e is !!! c ed i 1 h ! !! t n t t ! o n i t ! t c a a u i t t a Sta me B re St g re Using tal each ti g s To is ci i of Int t c i a at St St Static !! at!!!! S gre s i c i t ta e ! at! c ati t S i r sg
COPYRIGHT 2010: Dr. David Scanlan, CSUS Lifetime of Variables (Static) Try to use S of mo t dule-l atic for ac cumu evel v lation ariabl of tot es. After als in we le stead arn ab will n out ar o long gume er be variab n allow les. ed to ts and par amete use m r odule -level s you Fig-3_0000
COPYRIGHT 2010: Dr. David Scanlan, CSUS Summary of Local and Module-level Variables Fig-3_0000 SUMMARY Local Variables: 1. They are declared in a sub-procedure, such as a button_click sub-procedure. 2. They are useful only in the sub-procedure in which they are declared. 3. They are re-created and set to zero each time the sub-procedure is executed. This is NOT true if the local variable is declared using Static instead of Dim. Most of the time it is better to use Static instead of declaring a variable at the module level. Module-level Variables: 1. They are declared in the Declaration Section of a Form. 2. They are useful in ALL sub-procedures anywhere in the Form. 3. They are created and set to zero only when the program is first run. 4. They retain the last assigned value until the program is STOPPED. IMPORTANT: If the local variable or the module-level variable is a STRING, it is initialized to a null value. In other words, no characters are in the string…it is "empty. "
COPYRIGHT 2010: Dr. David Scanlan, CSUS Converting to the Correct Data Type CASTING
COPYRIGHT 2010: Dr. David Scanlan, CSUS CASTING FUNCTIONS: • FUNCTIONS: Perform an action and return a value. • CASTING: Converting from one type of data to another. • EXAMPLES: • CDec(txt. Hourly. Wage. Text) • Converts text in numbers to a decimal value for arithmetic operations. • CInt(txt. Show. Tickets. Sold. Text) • Converts text in numbers to an integer value for arithmetic operations. • CStr(Int. Id. Number) • Converts an integer to text so it can be assign to a text property in an object such as a label for display purposes. • OTHERS: • Clng(Argument) 'Convert to a Long data type • CSng(Argument) 'Convert to a Single data type • CDbl(Argument) 'Convert to a Double data type • ARGUMENT: The value that the function uses that is enclosed in parentheses. • EXAMPLES: • CDec(Argument) • CInt(Argument) • CStr(Argument) • PARSING: Means to examine, character by character. • The arguments above are being examined character by character and the result is another data type.
CASTING COPYRIGHT 2010: Dr. David Scanlan, CSUS CASTING FUNCTIONS: • IMPORTANT • The CInt() function first converts the argument to numeric and then rounds, if necessary to produce an integer. • Unexpected rounding method for this function: • CInt() ROUNDS TO THE NEAREST EVEN NUMBER: • CInt(1. 5) rounds to 2 This strange rounding • CInt(. 5) rounds to 0 only applies to "Cint") • CInt(2. 5) rounds to 2 • CInt(12. 5 rounds to 12) • If you are working with numbers with decimal points, use CDec() unless you have a need for scientific notation. In that case, use single-precision floating point or double-precision floating point numbers. 8. 0 ntin o c en m ste y s g e This ng stra t in d e u 20 B V o e b s ha din n u ro Book (Gaddis notes) Gaddis should be correct, but VB 2008 is not correct. int. Count = CInt(12. 5) ‘int. Count value is 13
CASTING COPYRIGHT 2010: Dr. David Scanlan, CSUS EXAMPLE: Dim int. X As Integer int. X = CInt("123. 45" Result: int. X will contain 123 Note that. 45 will be dropped. PARSING STRINGS DURING CASTING Content of String Argument CInt(Argument) CDec(Agrument) "123. 45" 123. 45 "$100" 100. 00 "1, 000. 00 " 1000. 00 "A 123" (error) "-5" -5 -5. 00 "5 -" Result of casting -5. 00 "(5)" -5 -5. 00 "0. 01" 0 0. 01 "0. 5" 0 0. 50 "1. 5" 2 1. 50 (blank) (error)
COPYRIGHT 2010: Dr. David Scanlan, CSUS Arithmetic Operations
COPYRIGHT 2010: Dr. David Scanlan, CSUS Arithmetic Operations ARITHMETIC OPERATORS Operator Operation Example + Addition X=Y+3 - Subtraction X=Y-3 * Multiplication X=Y*3 / Division X=Y/3 Integer division X=Y3 X=83 (Any remainder gets dropped. ) (X = 2) Modulus X = 9 Mod 4 ^ Exponentiation X=Y^2 s rn tu Re Mod (X = 1 ) ( Y is raised to the second power) e th m Re r. de n ai
COPYRIGHT 2010: Dr. David Scanlan, CSUS Arithmetic Operations ORDER OF PRECEDENCE ORDER 1. Any operation inside parentheses (Multiple operations within parentheses use rules of precedence) 2. Exponentiation (Multiple ^ operations are performed left to right) 3. Multiplication and division (Multiple * or / operations are performed left to right) 4. Integer division (Multiple operations are performed left to right) 5. Modulus (Multiple Mod operations are performed left to right) 6. Addition and subtraction (Multiple * or / operations are performed left to right) All students MUST memorize this order.
Arithmetic Operations COPYRIGHT 2010: Dr. David Scanlan, CSUS ORDER OF PRECEDENCE Calculation examples: Calculations Result X = (2 + 2) / 2 X=2+2/2 X=3 X=2 X = 2 ^ (2 * 2) X = 16 X=2^2*2 X=8 X=2*3+4 -6 / 2*5 (X = 6 + 4 - 6 / 2 * 5) (X = 6 + 4 - 3 * 5) (X = 6 + 4 - 15) (X = 10 - 15) (X = -5) X = -5 IMPORTANT: In this course, ALWAYS use parentheses to control the order of calculations. This makes the equation more readable.
Assignment Operation COPYRIGHT 2010: Dr. David Scanlan, CSUS ASSIGNMENT OPERATOR: = • Technically speaking, this is the only purely assignment operator: = • It means to take the value on the right side of the assignment operator and assign it to the variable on the left side. • Example: dec. X = dec. Y + dec. Z Steps: the CPU adds what is in memory location dec. Y to what is in memory location dec. Z and places the result in memory location dec. X = dec. Y + dec. Z CPU dec. X dec. Y dec. Z 8. 0 4. 5 3. 5 The CPU adds the contents of locations dec. Y and dec. Z. Then "assigns" the result to dec. X.
Assignment Operation COPYRIGHT 2010: Dr. David Scanlan, CSUS HOW ACCUMULATING VALUES USING: = • One of the most common operations in programming is the accumulation of values. • Example: dec. Total. Sales = dec. Total. Sales + dec. Sale Steps: the CPU adds what is in memory location dec. Total. Sales to what is in memory location dec. Sale and place the result in memory location dec. Total. Sales. Same location in memory. CPU dec. Total. Sales 15. 0 dec. Total. Sales 10. 0 dec. Sales 5. 0 The CPU adds what is in memory location dec. Total. Sales (10. 0) to what is in memory location dec. Sale (5. 0) and places the result (15. 0) in memory location dec. Total. Sales. NOTE: There are only two locations here, not three.
Assignment Operation COPYRIGHT 2010: Dr. David Scanlan, CSUS HOW TO DECREMENT A VALUE USING: = • Decrementing a value is also common in programming • Example: int. Counter as Integer int. Counter = 10 int. Counter = int. Counter - 1 Steps: The CPU subtracts 1 from what is memory location int. Counter and assigns the result to int. Counter. Same location in memory. The CPU subtracts 1 from what is in memory location int. Counter (10) and assigns the result (9)to int. Counter. CPU int. Counter 9 int. Counter 10 1 NOTE: There are only two locations here, not three.
COPYRIGHT 2010: Dr. David Scanlan, CSUS Shortcut Assignment Operation SHORTCUT ASSIGNMENT OPERATORS: +=, -=, *=, /=, =, and &= • Technically speaking, these operators do more than assignment. • Many experts say we should refer to these operators collectively as "shortcut assignment operators" and individually as indicated below: • += Addition-assignment operator • -= Subtraction-assignment operator • *= Multiplication-assignment operator • /= Division-assignment operator • = Integer-division assignment operator • &= Concatenation-assignment operator Operator dec. Variable += 5 D dec. Variable -= 5 D dec. Variable *= 5 D dec. Variable /= 5 D int. Variable = 5 I str. Variable &= "a string" Same as dec. Variable = dec. Variable + 5 D dec. Variable = dec. Variable - 5 D dec. Variable = dec. Variable * 5 D dec. Variable = dec. Variable / 5 D int. Variable = int. Variable 5 I str. Variable = str. Variable & "a string"
Shortcut Assignment Operation COPYRIGHT 2010: Dr. David Scanlan, CSUS SHORTCUT ASSIGNMENT OPERATORS: +=, -=, *=, /=, =, and &= For this class, do not use the shortcut assignment operators; however, you must know them. Both methods are used in the real world. Why not use the shortcut method? The long method is clearer as to what is actually happening in the computer. This is best for a beginning programmer. dec. X = dec. X + dec. Y VS. dec. X += dec. Y CPU dec. X dec. Y 7. 0 5. 0 2. 0 The CPU adds the contents of locations dec. X and dec. Y. Then "assigns" the result to dec. X.
COPYRIGHT 2010: Dr. David Scanlan, CSUS Option Explicit On/Off Option Strict On/Off Note: Always use Option Strict On
COPYRIGHT 2010: Dr. David Scanlan, CSUS Option Explicit On/Off
OPTION EXPLICIT ON/OFF COPYRIGHT 2010: Dr. David Scanlan, CSUS Option Explicit On/Off Option Explicit Off will allow you to use variable names in your code without first declaring them with a Dim statement. (NEVER turn Option Explicit off. ) • Place the Option Explicit statement at the beginning of the code in Form 1. • If you use Option Explicit Off, the data type will become Object which will hold any type of data. That is, if you do not declare the variable. • MAJOR PROBLEM: a misspelled variable name will create a new variable and lots of debugging headaches. • Hours = Hour + 1 • Total. Sales = Totl. Sales + 120. 00 Spelling errors. Option Explicit On will force the programmer to declare all variables with a Dim statement before using them. By default, Option Explicit is turned On in Visual Basic. NET.
COPYRIGHT 2010: Dr. David Scanlan, CSUS Option Strict On/Off Be sure to place this statement in all your assignments: Option Strict On
COPYRIGHT 2010: Dr. David Scanlan, CSUS OPTION STRICT ON/OFF Option Strict On keeps the programmer from assigning oranges to apples and apples to oranges to apples txt. Variable. Text = int. Variable apples to oranges dec. Variable = str. Variable
OPTION STRICT ON/OFF COPYRIGHT 2010: Dr. David Scanlan, CSUS Option Strict On keeps the programmer from assigning a big basket of apples to a smaller one. If you do this, you will loose some apples. Not allowed shr. Variable = lng. Variable Short 32, 767 Long 9, 223, 372, 036, 854, 775, 807
COPYRIGHT 2010: Dr. David Scanlan, CSUS OPTION STRICT ON/OFF Place Option Strict On here. . . at the top of Form 1 code. This is from VB 2003. You do not have this line of code in VB 2008.
OPTION STRICT ON/OFF COPYRIGHT 2010: Dr. David Scanlan, CSUS Option Strict On/Off Option Strict On 1. All variables must be declared. (No need to use Option Explicit On) 2. Option Strict On does not allow any of these implicit (automatic) conversions: a. from a "wider" type of data to a narrower one. shr. Variable = lng. Variable (Short = 16 bits, Long = 64 bits) b. between string and numeric data types. dec. Variable = str. Variable = dec. Variable (Totally different type of data) c. Exception: (Conversion from a narrow type of the same data type to a wide. ) EXAMPLES: lng. Variable = shr. Variable (Long = 64 bits, Short = 16 bits) This conversion is OK. Long and Short are both integers but differ in precision. dbl. Variable = sng. Variable (Double = 64 bits, Single = 32 bits) Double and Single are both floating point but differ in precision. ) In this course, NEVER use implicit conversions. Option Strict On is good training for beginning programmers. ALWAYS USE CONVERSION FUNCTIONS FOR DATA TYPE CONVERSIONS. By default Option Strict is turned Off in Visual Basic. NET.
COPYRIGHT 2010: Dr. David Scanlan, CSUS Formatting Data Format. Currency() Format. Number() Format. Percent() Format. Date. Time()
COPYRIGHT 2010: Dr. David Scanlan, CSUS Format. Currency()
COPYRIGHT 2010: Dr. David Scanlan, CSUS Formatting Data Format. Currency(Numeric. Expression. To. Format) -- Simple Form General Form of Format. Currency() function: 1. Format. Currency() function returns a string of characters: a. $1, 200. 50 (Formats as dollars and cents. ) b. $ (Dollar sign) c. , (Commas as necessary) d. . (Decimal point) e. . 00 (Two digits to the right of the decimal point) f. $0. 35 (Leading zero digit for values below $1. 00, such as 35 cents. ) EXAMPLE Dim dec. Minute. Rate As Decimal dec. Minute. Rate = 0. 35 D lbl. Minute. Rate. Text = Format. Currency(dec. Minute. Rate) Returns string data type. RESULT DISPLAYED IN LABEL AS: $0. 35 EXAMPLE Returns string data type. Dim dec. Hourly. Rate As Decimal dec. Hourly. Rate = 123. 45 D lbl. Hourly. Rate. Text = Format. Currency(dec. Hourly. Rate) RESULT DISPLAYED IN LABEL AS: $123. 45
COPYRIGHT 2010: Dr. David Scanlan, CSUS Formatting Data Format. Currency(Numeric. Expression. To. Format) -- General Form of Format. Currency() function: You must know that the General Form has more options. If needed, you can look them up in VB. NET help, or use Google. The Simple Form is adequate for most business programs. However, you should know how to control the number of digits to the right of the decimal point: Example: Number of digits Format. Currency(Expression. To. Format, 4) This will result in placing 4 digits to the right of the decimal point. $1, 234. 9500; $234. 0000; $99. 9999 No decimal point, no digits. Format. Currency(Expression. To. Format, 0) This will result in a number with no decimal point, and of course no digits to the right of the decimal point: $1, 234; $99
COPYRIGHT 2010: Dr. David Scanlan, CSUS Format. Number()
COPYRIGHT 2010: Dr. David Scanlan, CSUS Formatting Data Format. Number(Numeric. Expression. To. Format) -- Simple Form of Format. Number() function: 1. Format. Number() function returns a string of characters: a. 1, 200. 50 (Formats using commas and two digits to the right of the decimal point. ) b. , (Commas as necessary) c. . (Decimal point) d. . 00 (Two digits to the right of the decimal point) e. 0. 35 (Leading zero digit for values below 1. 00 dollar, such as 35 cents. ) EXAMPLE Returns string data type. Dim dec. Minute. Rate As Decimal dec. Minute. Rate =. 35 D lbl. Minute. Rate. Text = Format. Number(dec. Minute. Rate) RESULT DISPLAYED IN LABEL AS: 0. 35 Returns string data type. EXAMPLE Dim dec. Hourly. Rate As Decimal dec. Hourly. Rate = 123. 45 D lbl. Hourly. Rate. Text = Format. Number(dec. Hourly. Rate) RESULT DISPLAYED IN LABEL AS: 123. 45
COPYRIGHT 2010: Dr. David Scanlan, CSUS Formatting Data Format. Number(Numeric. Expression. To. Format) -- General Form of Format. Number() function: You must know that the General Form has more options. If needed, you can look them up in VB. NET help, Google. The Simple Form is adequate for most business programs. However, you should know how to control the number of digits to the right of the decimal point: Example: Format. Number(Expression. To. Format, 4) Number of digits This will result in placing 4 digits to the right of the decimal point. 1, 234. 9500; 234. 0000; 99. 9999 No decimal point, no digits. Format. Number(Expression. To. Format, 0) This will result in a number with no decimal point, and of course no digits to the right of the decimal point: 1, 234; 99
COPYRIGHT 2010: Dr. David Scanlan, CSUS Format. Percent()
COPYRIGHT 2010: Dr. David Scanlan, CSUS Formatting Data Format. Percent(Numeric. Expression. To. Format) -- Simple Form of Format. Percent() function: Returns string data type. EXAMPLE Dim dec. Tax. Rate As Decimal dec. Tax. Rate =. 35 D lbl. Display. Tax. Rate. Text = Format. Percent(dec. Tax. Rate) RESULT DISPLAYED IN LABEL AS: 35. 00% EXAMPLE Returns string data type. Dim dec. Tax. Rate As Decimal dec. Tax. Rate =. 1234 D lbl. Display. Tax. Rate. Text = Format. Percent(dec. Tax. Rate) RESULT DISPLAYED IN LABEL AS: 12. 34%
COPYRIGHT 2010: Dr. David Scanlan, CSUS Formatting Data Format. Percent(Numeric. Expression. To. Format) -- General Form of Format. Percent() function: You must know that the General Form has more options. If needed, you can look them up in VB. NET help, or use Google The Simple Form is adequate for most business programs. However, you should know how to control the number of digits to the right of the decimal point: Number of digits Example: Format. Percent(Expression. To. Format, 4) This will result in placing 4 digits to the right of the decimal point. No decimal point, no digits. 35. 1234%; 99. 1234% Format. Percent(Expression. To. Format, 0) This will result in a number with no decimal point, and of course no digits to the right of the decimal point: 35%; 99%; 45%
COPYRIGHT 2010: Dr. David Scanlan, CSUS Formatting Data Format. Percent(Numeric. Expression. To. Format) -- General Form EXAMPLE Dim dec. Tax. Rate As Decimal dec. Tax. Rate =. 1234 D lbl. Display. Tax. Rate. Text = Format. Percent(dec. Tax. Rate, 0) RESULT DISPLAYED IN LABEL AS: 12% Number of digits to the right of the decimal point. EXAMPLE Dim dec. Tax. Rate As Decimal dec. Tax. Rate =. 12345 D lbl. Display. Tax. Rate. Text = Format. Percent(dec. Tax. Rate, 3) RESULT DISPLAYED IN LABEL AS: 12. 345%
COPYRIGHT 2010: Dr. David Scanlan, CSUS Format. Date. Time()
Formatting Data COPYRIGHT 2010: Dr. David Scanlan, CSUS Format. Date. Time(Expression. To. Format [, Named. Format]) 1. Formats a date and/or time. 2. Expression. To. Format: a. Can be a string that holds a date or time value. b. Can be a date type variable. c. Can be a function that returns a date. Note: these formats use the computer's regional settings. 3. If you omit "Named. Format" the Format. Date. Time function returns the date using the General. Date format: "10/30/03 3: 22: 18 PM" Named. Format Example Date. Format. General. Date. Format. Long. Date. Format. Short. Date. Format. Long. Time Date. Format. Short. Time 10/30/03 3: 22: 18 PM Thursday, October 30, 2003 10/30/03 9: 30: 45 AM 21: 05 (Military time) EXAMPLE: Label 1. Text = Format. Date. Time("10/30/03", Date. Format. Long. Date) Result: Friday, October 30, 2003
Additional notes from the textbook (Gaddis) 3. 5 Formatting Numbers and Dates Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
The To. String Method n n Converts the contents of a variable to a string Every VB data type has a To. String method Uses the form Variable. Name. To. String n Value in Variable. Name is converted to a string For example Dim number as Integer = 123 lbl. Number. text = number. To. String n Converts integer 123 to string “ 123” Then assigns the string to the text property of the lbl. Number control. Note: the value (123) in the variable “number” stays as an Integer. Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 3 - 78
To. String Method with Format String n ” “c m n Can pass a format string to the To. String method n Indicates how you want to format the string For example ns ea Dim dbl. Sample as Double Dim str. Result as String dbl. Sample = 1234. 5 str. Result = dbl. Sample. To. String(“c”) y n nc re r cu n The value “c” is a format string Converts 1234. 5 to currency format $1, 234. 50 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 3 - 79
Types of Format Strings n n n “N” or “n” – number format includes commas and displays 2 digits to the right of the decimal “F” or “f” – fixed point format 2 digits to the right of the decimal but no commas “C” or “c” – currency format includes dollar sign, commas, and 2 digits to the right of the decimal “P” or “p” – percent format multiplies number by 100 and displays with a trailing space and percent sign The computer’s regional settings determine some format items such as currency symbol Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 3 - 80
Specifying Decimal Positions n n Can add an integer to the format string to indicate number of digits to display after the decimal point Rounding occurs when displaying fewer decimal positions than the number contains as in the 2 nd line Number Value Format String To. String() Value 12. 3 “n 3” 12. 348 “n 2” 12. 300 12. 35 1234567. 1 “n” 123456. 0 “f 2” . 234 “p” -1234567. 8 “c” Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 1, 234, 567. 10 123456. 00 23. 40 % ($1, 234, 567. 80) Slide 3 - 81
Specifying Integer Leading Zeros n n “d” Can specify a minimum width when displaying an integer value Leading zeros are inserted to meet the minimum width if needed Integer Value Format String To. String() Value 23 “d” 23 “d 4” 1 “d 2 23 0023 01 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 3 - 82
File: Ch 3 In. Class. ProjectsLifetime. Local. Variables. ppt Start of In-Class Program Chapter 3: Time Date Example Directions: 1. Create the GUI on the right, but exclude the code text. 2. Pressing any button will display the Date and/or Time in the Labels. 3. Use the code on the next page to complete the program. Exclude this code text. Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
File: Ch 3 In. Class. ProjectsLifetime. Local. Variables. ppt Chapter 3: Time Date Example End of In-Class Program Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Retrieving the Current Date/Time n A series of keywords yields the current date, current time, or both Description Date & Time only Date only n Keyword Now Time. Of. Day Today Example dat. Current = Now dat. Curr. Time = Time. Of. Day dat. Curr. Date = Today Variables dat. Current, dat. Curr. Time, and dat. Curr. Date must be declared as Date data types Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 3 - 85
Formatting Dates and Times n n The To. String method can format a Date or Date. Time value in a variety of ways If the date is 4/7/2015 and the time is 3: 22: 18 PM Format String Description To. String() Value “d” Short Date 4/7/2015 “D” Long Date Monday, April 7, 2015 “t” Short Time 3: 22 PM “T” Long Time 3: 22: 18 PM “F” Full Date/Time Monday, April 7, 2015 3: 22: 18 PM n Tutorial 3 -8 provides an opportunity to work with number formatting concepts Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 3 - 86
Start of Program Ch 3: Simple TRY/CATCH Directions: 1. Create the GUI below. 2. Enter a numeric value only (123) and the result should look like Example 1. Enter a value that is not total numeric (12 A) and the result should look like Example 2. 3. Use the code on the next slide and read the comments. 4. Set a Break. Point. Then single step through the program and watch the program execution flow. Example 1 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Example 2
Ch 3: Simple TRY/CATCH Public Class Form 1 'SIMPLE TRY/CATCH Private Sub Button 1_Click(By. Val sender As System. Object, By. Val e …… Try ' Place Textbox. Text between the Try and the Catch. Label 1. Text = Format. Currency(CDec(Text. Box 1. Text)) Catch Use. Any. Variable. Name As Invalid. Cast. Exception ' This code will execute if there is an Invalid. Cast. Exception. ' In other words, if CDec cannot convert what is in the ' Text property of the Text. Box to a valid numeric value. Msg. Box("Only Use Numbers", Msg. Box. Style. Exclamation) End Try ' If there is no Invalid. Cast. Exception program execution will jump ' to the End Try without executing the code in the Catch area. End Sub End Class End of Program Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley General Information: For each Text. Box, use a separate Try/Catch.
COPYRIGHT 2010: Dr. David Scanlan, CSUS Try/Catch Blocks
COPYRIGHT 2010: Dr. David Scanlan, CSUS Try/Catch Blocks PURPOSE: Helps keep the program from "crashing" Example of exceptions (errors) handled: 1. Divide by zero. 2. Conversion functions such as Cint(argument) and CDec(argument) cause exceptions when: a. Non-numeric data is used as the argument. b. Converting Textbox. text when a blank is in the text property. 3. Failure of an input/output file operation, such as reading or writing to a disk. 4. Not enough memory (RAM) to create an object from a class. 5. Assigning a number to a variable which is larger than its data type can hold. Terms: 1. Error trapping: Catching exceptions as they happen when the program is running. 2. Error handling: Coding to take care of the exception so that the program (1) gives appropriate feedback to the user and (2) keeps the program from crashing.
Try/Catch Blocks COPYRIGHT 2010: Dr. David Scanlan, CSUS Try/Catch Blocks Some of the many Exception Classes: Exception Caused by: Invalid. Cast. Exception Failure of a conversion function, such as CInt or CDec. Usually caused by blank or nonnumeric data. Arithmetic. Exception A calculation error, such as a division by zero or overflow of a variable (assigning to a variable a value larger than it can hold. Example: shr. Variable. Name = 125, 000 Note: a short data type can only hold a max of 32, 767. System. IO. Endof. Stream. Exception reading from or writing to a file. Out. Of. Memory. Exception Failure of an input or output operation such as Not enough memory to create and object. Exception Triggers on any problem. Use this exception ONLY if the ones above do not cover the error you intend to trap. Attention
COPYRIGHT 2010: Dr. David Scanlan, CSUS SIMPLE PROGRAM Try/Catch
COPYRIGHT 2010: Dr. David Scanlan, CSUS
COPYRIGHT 2010: Dr. David Scanlan, CSUS
COPYRIGHT 2010: Dr. David Scanlan, CSUS Less Simple Program Try/Catch Range Check Numerator Result = Denominator
COPYRIGHT 2010: Dr. David Scanlan, CSUS Numerator Denominator Result
COPYRIGHT 2010: Dr. David Scanlan, CSUS Run the VB program on Try/Catch. It is in this directory.
COPYRIGHT 2010: Dr. David Scanlan, CSUS This is from VB 2003. You do not have this line of code in VB 2008.
COPYRIGHT 2010: Dr. David Scanlan, CSUS bln. Error. Flag: Don't be concerned with understanding the course. It will be used extensively later. this flag at this point in
COPYRIGHT 2010: Dr. David Scanlan, CSUS bln. Error. Flag: Don't be concerned with understanding the course. It will be used extensively later. this flag at this point in
COPYRIGHT 2010: Dr. David Scanlan, CSUS
COPYRIGHT 2010: Dr. David Scanlan, CSUS
COPYRIGHT 2010: Dr. David Scanlan, CSUS That's all folks.
- Slides: 103