Programming Language 2 (PL2)
337.1.1 - Explain rules for constructing various variable types of language 337.1.2 Identify the use of arithmetical and logical operators 337.1.3 Explain the rules of language statement construction
Variables: computer memory locations used to store data while an application is running Use a meaningful variable name that reflects the purpose of the variable Use camel casing for variable identifiers Variable names should conform to naming rules
Figure 3-1: How to name a variable
Each variable must be assigned a data type Data type: the type of data the variable can store Each data type is a class Unicode: Universal coding scheme for characters Assigns a unique numeric value to each character
Integer types Byte Short Integer Long Floating-Point types Single Double Decimal Other data types Boolean Char String Date
For values that will always be a whole number Usually name a variable starting with a 3 or 4 letter prefix indicating the variable s type Data Type Naming Prefix Description Byte byt Unsigned integer from 0 to 255 Short shrt Signed integer from -32,768 to 32,767 Integer int Signed integer from -2,147,483,648 to 2,147,483,647 Long lng Signed integer from - 9,223,372,036,854,775,808 to 9,223,372,036,854,775,807
For values that may have fractional parts Single used most frequently Double sometimes used in scientific calculations Decimal often used in financial calculations Data Type Naming Prefix Description Single sng As large as 10 38 plus or minus, 7 decimal positions Double dbl As large as 10 308 plus or minus,15 decimal positions Decimal dec As large as 10 29 plus or minus, 29 decimal positions
Boolean variable naming prefix is bln Holds 2 possible values, True or False Char variable naming prefix is chr Holds a single character Allows for characters from other languages String variable naming prefix is str Holds a sequence of up to 2 billion characters Date variable naming prefix is dat or dtm Can hold date and/or time information
A string literal is enclosed in quotation marks The following code assigns the name Jose Gonzales to the variable strname Dim strname as string strname = "Jose Gonzales" An empty string literal can be coded as: Two consecutive quotation marks strname = "" Or by the special identifier String.Empty strname = String.Empty
Date data type variables can hold the date and time or both You can assign a date literal to a Date variable, as shown here: Dim dtmbirth As Date dtmbirth = #5/1/2010# A date literal is enclosed within # symbols All of the following Date literals are valid: #12/10/2010# #8:45:00 PM# #10/20/2010 6:30:00 AM#
A series of keywords yields the current date, current time, or both Description Keyword Example Date & Time Now dtmcurrent=now Time only TimeOfDay dtmcurrtime=timeofday Date only Today dtmcurrdate=today Variables datcurrent, datcurrtime, and datcurrdate must be declared as Date data types
Figure 3-2: Basic data types in Visual Basic
Declaration statement: used to declare, or create, a variable Declaration statement includes Scope keyword: Dim, Private, or Static Name of the variable Data type Initial value (optional) Numeric data types are automatically initialized to 0 String data type is automatically initialized to
Figure 3-3: How to declare a variable
Assignment statement: Used to assign values to properties of controls Used to assign values to variables Assignment operator: (=) Value on the right of the = operator is assigned to the variable on the left of the = operator
String: group of characters enclosed in quotation marks Literal constant: An item of data whose value does not change while the application is running Can be a numeric or a string literal constant A numeric literal without a decimal place is treated as an integer A numeric literal with a decimal place is treated as a Double type
Figure 3-4: How to assign a value to a variable
Method: a specific portion of a class s instructions that performs a task for the class TryParse method: Part of every numeric data type s class Used to convert a string to that numeric data type Argument: a value that is provided to a method Basic syntax of TryParse method has two arguments: String: string value to be converted Variable: location to store the result
If TryParse conversion is successful, the method stores the value in the variable If unsuccessful, a 0 is stored in the numeric variable
Figure 3-5: How to use the basic syntax of the TryParse method
Convert class: Contains methods for converting numeric values to specific data types Use the dot member access operator to separate the class name from the method name Commonly used methods of the Convert class include: ToDouble ToDecimal ToInt32 ToString
Figure 3-6: How to use the Convert class methods
Undeclared variable: a variable that does not appear in a declaration statement (such as Dim) Is assigned a data type of Object Misspelling a variable name can result in an undeclared variable unless Option Explicit is on Option Explicit On statement Appears in the General Declarations section of the Code Editor window (above Public Class statement) Enforces that all variables must be declared before being used
Option Infer Off statement: ensures that every variable is declared with a data type Implicit type conversion: occurs when you attempt to assign data of one type to a variable of another type without explicitly attempting to convert it If converted to a data type that can store larger numbers, the value is said to be promoted If converted to a data type that can store only smaller numbers, the value is said to be demoted Can cause truncation and loss of precision
Option Strict On statement: ensures that values cannot be converted from one data type to a narrower data type, resulting in lost precision Figure 3-8: Option statements entered in the General Declarations section
Figure 3-7: Rules and examples of type conversions
Arithmetic operators: used to perform calculations Precedence number: indicates the order in which an operation in an expression is performed If an expression has two operators with the same precedence, they are evaluated from left to right Use parentheses to change the order of evaluation Integer division operator (\): divides two integers and returns an integer value Modulus arithmetic operator (Mod): divides two numbers and returns the remainder
Figure 3-9: Most commonly used arithmetic operators and order of precedence
Figure 3-10: How to include arithmetic expressions in assignment statements
Line continuation character (_): Used to break up a long instruction into two or more physical lines Underscore must be preceded by a space and must appear at the end of a physical line A variable can store only one value at a time A second assignment statement on the same variable will replace its current value with the new value
Scope: indicates where the variable can be used Lifetime: indicates how long the variable remains in memory Variables can have module scope, procedure scope, or block scope Module scope: variable is declared in the form s Declarations section Variables declared within a procedure have either procedure scope or block scope
Procedure-level variable: declared within a procedure Use the Dim keyword in the declaration Procedure scope: only the procedure can use the variable With procedure-level scope, two procedures can each use the same variable names Comments: Used to internally document the procedure Are ignored by the compiler Appear in green in the Code Editor
Figure 3-11: The MainForm in the Sales Tax application Figure 3-12: Examples of using procedure-level variables
Module scope: variable can be used by all procedures in the form Module-level variable: Declared in the form s Declarations section Use Private keyword in declaration Module-level variables retain their values until the application ends
Figure 3-13: Example of using a module-level variable
Static Variables Static variable: Procedure-level variable that retains its value even after the procedure ends Retains its value until the application ends (like a module-level variable), but can only be used by the procedure in which it is declared A static variable has: Same lifetime as a module-level variable Narrower scope than a module-level variable Declared using the Static keyword
Figure 3-14: The MainForm in the Total Sales application Figure 3-15: Example of using a static variable
Named constant: memory location whose value cannot be changed while the application is running Declared using the Const keyword Good programming practice to specify the data type as well Many programmers use Pascal case for named constants Literal type character: forces a literal constant to assume a specific data type Named constants help to document the program code
Figure 3-16: How to declare a named constant
Figure 3-17: The MainForm in the Area Calculator application Figure 3-18: Example of using a named constant
Figure 3-19: Sunshine Cellular interface
Figure 3-20: Sunshine Cellular TOE chart
Pseudocode: short phrases that describe the steps a procedure needs to take to accomplish its goal Figure 3-21: Pseudocode for the Sunshine Cellular application
Flowchart: uses standardized symbols to show the steps a procedure must take to accomplish its goal Can be used in place of pseudocode for planning Three symbols: Start/stop symbol (oval): indicates start and stop points Process symbol (rectangle): represents tasks Input/output symbol (parallelogram): represents input or output tasks Flowlines: connect the symbols to show the direction
Figure 3-22: Flowcharts for the Sunshine Cellular application
Figure 3-23: Pseudocode for the calcbutton s Click event procedure
Figure 3-24: Named constants and variables for the calcbutton s Click event procedure
Figure 3-25: Declaration statements entered in the calcbutton s Click event procedure
Figure 3-26: User input assigned to variables
Figure 3-27: Completed calcbutton s Click event procedure
Focus method: moves the focus to a specified control when the application is running Figure 3-28: Pseudocode for the clearbutton s Click event procedure
Figure 3-29: The Sunshine Cellular application s code
Figure 3-29: The Sunshine Cellular application s code (continued)
Bug: an error in the program code Valid data: data that the application is expecting Invalid data: data that is unexpected Debugging: process of locating and correcting errors in a program
Syntax error: an error that violates the programming language s syntax Usually caused by mistyping Logic error: occurs when you enter an instruction that does not give the expected results Test a program with both valid and invalid data
Figure 3-30: Result of testing the application using valid data
Figure 3-31: Result of testing the application using invalid data
Formatting: specifying the number of decimal places and any special characters to display ToString method of a variable can be used to format a number Format specifier: specifies the type of formatting to use Precision specifier: controls the number of significant digits or zeros to the right of the decimal point
Figure 3-32: How to format a number
Converts the contents of a variable as a string Every VB data type has a ToString method Uses the form VariableName.ToString Value in VariableName is converted to a string For example: Dim number As Integer = 123 lblnumber.text = number.tostring Converts integer 123 to string "123" Then assigns the string to the text property of the lblnumber control
Can pass a format string to the ToString method Indicates how you want to format the string For example Dim dblsample As Double Dim strresult As String dblsample = 1234.5 strresult = dblsample.tostring("c") The value "c" is a format string Converts 1234.5 to currency format $1,234.50
Format String Description N or n Number format includes commas and displays 2 digits to the right of the decimal F or f E or e C or c P or p Fixed point format 2 digits to the right of the decimal but no commas Exponential format displays values in scientific notation with a single digit to the left of the decimal point. The exponent is marked by the letter e, and the exponent has a leading + or - sign. Currency format includes dollar sign, commas, and 2 digits to the right of the decimal Percent format multiplies number by 100 and displays with a trailing space and percent sign
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 ToString() Value 12.3 n3 12.300 12.348 n2 12.35 1234567.1 n 1,234,567.10 123456.0 f2 123456.00 123456.0 e3 1.235e+005.234 p 23.40% 1234567.8 c ($1,234,567.80)
Can specify a minimum width when displaying an integer value Leading zeros are inserted to meet the minimum width if needed Number Value Format String ToString() Value 23 D 23 23 D4 0023 1 D2 01
The ToString method can format a Date or DateTime value in a variety of ways If the date is 8/10/2010 and the time is 3:22 PM Format String Description ToString() Value d Short Date "8/10/2010" D Long Date "Tuesday, August 10, 2010" t Short Time "3:22 PM" T Long Time "3:22:00 PM" F Long Date & Time "Tuesday August 10, 2010 3:22:00 PM"
Figure 3-33: calcbutton s modified Click event procedure
Figure 3-34: Formatted output shown in the interface
Figure 3-36: User interface
Figure 3-44: Pseudocode