View
233
Download
40
Category
Tags:
Preview:
DESCRIPTION
CSCI 3131.01 Chapter 3 Variables and Calculations Instructor: Bindra Shrestha University of Houston – Clear Lake. Acknowledgement Dr. Xinhua Chen And Starting Out with Visual Basic 2010 by Tony Gaddis and Kip Irvine. Topics Gathering Text Input Variables and Data Types - PowerPoint PPT Presentation
Citation preview
CSCI 3131.01
Chapter 3 Variables and Calculations
Instructor: Bindra Shrestha
University of Houston – Clear Lake
Acknowledgement
Dr. Xinhua Chen
And
Starting Out with Visual Basic 2010 by Tony Gaddis and Kip Irvine
Topics
•Gathering Text Input•Variables and Data Types•Performing Calculations•Mixing Different Data Types•Formatting Numbers and Dates•Exception Handling•The Load Event Procedure•Debugging – Locating Logic Errors
txtUserName
lblGreeting
btnClose
btnShowGreeting
Use TextBox Control to Get User Input
Use the Text property of the TextBox to retrieve user input.Syntax: nameOfTextBox.TextUse the Clear method to clear TextBox
nameOfTextBox.Clear()
The Use of TextBox
•Use the Text property of the TextBox to retrieve user input.Syntax: nameOfTextBox.Text
•Use the Clear method to clear TextBoxSyntax: nameOfTextBox.Clear()
•Display the contents of a TextBox with a LabelSyntax: nameOfLabel.Text = nameOfTextBox.Text
•Display a string with a TextBoxSyntax: nameOfTextBox.Text = StringValue
String Concatenation
Use the concatenation operator (&) to concatenate strings.
Examples:
lblGreeting.Text = "Hello " & txtUserName.Text
lblGreeting.Text = lblGreeting.Text & ". " & _"How are you? "
The Focus Method
The controls that are capable of receiving some sort of input, such as TextBox and Button, may have focus.
Syntax of Focus:
nameOfControl.Focus()
Example:
txtFirstName.Focus
Tab Order
The focus moves from one control to another when the user presses the Tab key.
The order in which controls receive focus depends on the value of the TabIndex property and TabStop property.
Only if the TabStop property is True can the control receive focus.
The TabIndex can be set using the property window and the View->Tab Order menu item.
Assigning Keyboard Access Keys to Buttons
Windows applications almost always provide quick access to buttons using Alt-<key> combination.
For example, the Exit button blow can be access usingAlt-x
To enable keyboard access to the Exit button, set the Text property of the button as E&xit
How to Display “&” on a Button or a Label?
Use double ampersand (&&) to display one “&” on a Button or a Label.
Example:Set the Text property of a button as
Beans && Creammakes the button display as
Beans & Cream
Accept Buttons and Cancel Buttons
An accept button is clicked when the user presses the Enter key.
A cancel button is clicked when the user presses the Esc key.
In the form’s property window, you may set the accept button and the cancel button.
Variables and Data Types
•Variables are computer memory locations the application can access while running.
•An variable can be used do•Copy and store values entered by the user•Perform arithmetic on numeric values•Test values to determine that they meet some criterion•Temporarily hold and manipulate the value of a control property•Remember information for later use in a program
•Every variable has a name, data type, scope, and lifetime.
Variable Names
Visual Basic program uses identifiers to name variables, subprograms, classes and modules.
Rules of creating Visual Basic identifiers:
(1) The first character must be a letter or an underscore;(2) Other characters, if any, must be the combination of a
letter, an underscore, or a digit.(3) Maximum length of an identifier is 16383; however, the
recommended maximum length is 32.(4) A Visual Basic reserved word cannot be used as an
identifier.
Naming Conventions
(1) Hungarian notationUse the first three or more characters to represent the type and
the remaining characters to represent the purpose of the identifier
Example:intMax
(2) New notation that does not include the data type prefix, but include the purpose of the identifier only. If the identifier is formed using multiple words, make the first word lower case and make the first letter of other word(s) capitalized. This is called camel case.Example:
firstName
Valid Identifier_sum
strProduct
getSize
Item_222
MAX_HOURS
Invalid Identifier
13Users
get Size
box-22
IsEmpty?
Integer
Declaring a Variable
Syntax[Dim | Private | Static] variablename As datatype [ =initialvalue]
ExamplesDim dblCarPayment As DoubleDim decItemPrice As Decimal
Dim blnIsDataOk As Boolean = True
Dim strStudentName As StringDim intAge As Integer
Dim strName As String = String.Empty
Integer Data Types
Data Type
Naming Prefix
Description
Byte byt Unsigned integer from 0 to 255Short shrt Signed integer from -32,768 to 32,767Integer int Signed integer from -2,147,483,648 to 2,147,483,647Long lng Signed integer from -9,223,372,036,854,775,808
to 9,223,372,036,854,775,807
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
Floating-Point Data Types
Data Type
Naming Prefix
Description
Single sng As large as 1038 plus or minus, 7 decimal positionsDouble dbl As large as 10308 plus or minus,15 decimal positionsDecimal dec As large as 1029 plus or minus, 29 decimal positions
For values that may have fractional parts Single used most frequently Double sometimes used in scientific calculations Decimal often used in financial calculations
Other Common Data Types
• 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– Can hold date and/or time information
Integer Literals
A sequence of digit from 0 to 9 with optional sign makes an integer literal. Comma should not be included.
Use of type identifier, I, L and S:I: Integer literal (This is the default for integer literals)L: Long integer literalS: Short integer literal
Examples:1000L1234S
Floating-Point Literals
Floating-point literals can be written in either fixed-point or scientific notation.
Examples:
Fixed-point: 342.32Scientific notation: 4.73454E+4
This is Visual Basic’s notation for 4.73454 10-4.The letters F, R, D are used to indicate Single, Double and Decimal literals.
If no letter is appended to a floating-point literal, it is treated as Double.
Char Data Type
Variables of Char holds one Unicode character, which is a two-byte character. Use quotation marks and c to denote a Char literal.
Dim chrLetter As CharchrLetter = " A " c
String Data TypeA variable of type String can refer to zero to about 2 billion characters. Use quotation marks to create a string literal.
Dim strName As StringstrName = " Jose Gonzalez "
Date Data Type
A variable of type Date can hold date and time information. A date literal is defined using a pair of # signs.
Examples:
Dim dtmBirth As DatedtmBirth = #5/1/2008#
Dim dtmStartTime As DatedtmStartTime = #9/25/2008 7:00 PM#
The Object Data Type
If a variable is declared without data type, the Object data type is assumed by the Visual Basic compiler. The prefix for a variable of Object is obj, such objSender.
The Object type is the most flexible type, because a variable of Object type can store different type of data at the runtime of the program. For example, the same variable of Object type may store number 20 first then refer to string "John" next.
The flexibility of the Object type comes with inefficiency and more memory consumption.
Table of Literal Type Characters
Literal Type Character
Data type Example
S Short age = 35S
I Integer hours = 40I
L Long population = 20500L
D Decimal rate = 0.03D
F Single payRate =.03F
R Double sales = 2356R
C Char initial = "A"C
Assigning Data to an Existing Variable
Syntaxvariablename = value
ExamplesDim intQtyOrdered As IntegerintQtyOrdered = 500
Dim strFirstName As StringstrFirstName = "Mary"
Dim strZipCode As StringstrZipCode = zipTextBox.Text
Dim decTaxRate As DecimaldecTaxRate = .05D
Performing Calculations
Two types of operators in Visual Basic: unary and binary.
A unary operator requires only one operand, such as
-5-intCount+4
A binary operator requires two operands, such as
5 + 10intA + intB
Writing Arithmetic Expressions
Most commonly used arithmetic operators with their precedence.
Operator Operations Precedence number
^ exponentiation (raises a number to a power) 1
- negation 2
*, / multiplication and division 3
\ integer division 4
Mod modulus arithmetic 5
+, - addition and subtraction 6
Parentheses are commonly used to override the order of precedence. Parentheses have the highest precedence.
Operator Precedence Examples
6 * 2^3 + 4 / 2
6 * 8 + 4 / 2
48 + 4 / 2
48 + 2
50
6 / 2 * 2^3 + 4
6 / 2 * 8 + 4
3 * 8 + 4
24 + 4
28
The result is very different when the divide by 2 operation is moved from the end of the calculation to the middle.
Integer Division
The operator “\” performs integer division.
The decimal part of the quotient is discarded.
Example:
intHours = intMinutes \ 60
If intMinutes holds 100, intHours will hold 1 after the calculation.
Modulus
The modulus operator (MOD) performs integer division and returns only the reminder.
Example:
intRemainder = 17 MOD 3
intRemainder will hold 2 after the calculation.
Exponentiation
To calculate a variable x taken to the power of y, use this expression:
x ^ y
Example:
dblResult = 5.0 ^ 2.0 (mathematically, 52)
Getting the Current Date and Time
There are a few built-in functions available to get system date and time.
Description Keyword Example
Date & Time Now datCurrent=Now
Time only TimeOfDaydatCurrTime=TimeOfDay
Date only Today datCurrDate=Today
• Variables datCurrent, datCurrTime, and datCurrDate must be declared as Date data types
Variable Scope
A variable’s scope refers to the part of a program where the variable is accessible by programming statements.
1. Local Scope: A variable declared in a procedure has the local scope. This variable can only be accessed in the procedure where it is declared.
2. Class Scope: A variable declared inside a class but outside of any procedures has the class scope. This class-level variable can be accessed in any procedures of the class.
Variable Scope (Cont’d)
3. Global Scope: A variable declared outside of any class or procedure has the global scope. This variable can be accessed in any procedures.
Combined Assignment Operators
• Often need to change the value in a variable and assign the result back to that variableFor example: var = var – 5
Subtracts 5 from the value stored in var• Other examples:
x = x + 4 Adds 4 to xx = x – 3 Subtracts 3 from xx = x * 10 Multiplies x by 10
• VB provides for this common need with combined assignment operators
Combined Assignment Operators
These special assignment operators provide an easy means to perform these common operations:
Operator Usage Equivalent to Effect
+= x += 2 x = x + 2 Add to
-= x -= 5 x = x – 5 Subtract from
*= x *= 10 x = x * 10 Multiply by
/= x /= y x = x / y Divide by
\= x \= y x = x \ y Int Divide by
&= name &= last name = name & last Concatenate
Mixing Different Data Types
•Implicit Type ConversionIdeally, the variables of the same type should be used in a statement, e.g,
intSum = intA + intB 'All are integers
However, sometimes we may find it more convenient to use variables of different types in a statement, e.g.,
dblSum = dblA + intB 'Only intB is integer
Visual Basic attempts to convert intB to Double before the summation. This is called implicit conversion.
Mixing Different Data Types (Cont’d)
•Widening ConversionsWith widening conversions, a type that takes less memory is converted into a type that takes more memory. No loss of precision occurs with widening conversions. Examples:
Dim dblVar As Double = 1234
•Narrowing ConversionsWith narrowing conversions, a type that takes more memory is converted into a type that takes less memory. Loss of precision could occur with narrowing conversions. Examples:
Dim dblOne As Double = 1.2342376Dim sngTwo As Single = dblOne 'sngTwo = 1.234238
Converting Strings to Numbers
Visual Basic will try to convert string values to numbers in some cases.
Examples:
Dim sngTemperature As SinglesngTemperature = "12.13" 'Convert String into Single
Dim intCount As IntegerintCount = txtCount.Text 'Convert String into Integer
Option Strict
Implicit conversion is controlled by the setting of Option Strict.If Option Strict On/Off is specified in the beginning of a file, the setting affects the file. If the option is specified in the Project property screen, the setting affects the project.
Option Strict On: Disable implicit narrowing conversionOption Strict Off: Enable implicit narrowing conversion
When Option Strict On is in effect, the allowed implicit conversions are from left to right:
Byte Integer Long Decimal Single Double
Type Conversion Errors
With Option Strict On, the statement below generates a compilation error:
Dim intCount As Integer = "123"
With Option Strict Off, the statement below generates a runtime error:
Dim intCount As Integer = "abc123"
Named Constants
A named constant is a symbol for a literal. The value of the named constant cannot be changed while the application is running.
SyntaxConst constantname [As datatype] = expression
Examples:Const decPI As Decimal = 3.141593D
Const intMAXHOURS As Integer = 40
Private Const strCOTITLE As String = "ABC Company"
Explicit Type Conversion
When Option Explicit On is in effect, we must use some functions to convert some conversions explicitly.
A function is a named, self-contained body of code, which provide the output by manipulating the input.
Input(s) Function Output
Explicit Type Conversions
• The following narrowing conversions require an explicit type conversion– Double to Single– Single to Integer– Long to Integer
• Boolean, Date, Object, String, and numeric types represent different sorts of values and require conversion functions as well
Full List of Conversion Functions
• There are conversion functions for each data type
• CBool ( expr )
• CByte ( expr )
• CChar ( expr )
• CDate ( expr )
• CDbl ( expr )
• CDec ( expr )
• CInt ( expr )
• CLng ( expr )
• CObj ( expr )
• CShort ( expr )
• CSng ( expr )
• CStr ( expr )
Explicit Type Conversion Examples
• Rounding can be done with the CInt function
intCount = CInt(12.4) 'intCount value is 12
intCount = CInt(12.5) 'intCount value is 13
• CStr converts an integer value to a string
Dim strText as String = CStr(26)• CDec converts a string to a decimal value
Dim decPay as Decimal = CDec(“$1,500”)• CDate converts a string to a date
Dim datHired as Date = CDate(“05/10/2005”)
Invalid Conversions• Conversion functions can fail
Dim dblSalary as Double = CDbl("xyz")
Dim datHired as Date = CDate("05/35/2005")• String “xyz” can’t be converted to a number
• There’s no day 35 in the month of May
• These failed conversionscause a runtime error called an invalid cast exception
The Val Function
• The Val function is a more forgiving means of performing string to numeric conversions
• Uses the form Val(string) asshown here
• If the initial characters form a numeric value, the Val function will return that
• Otherwise, it will return a value of zero
Slide 3- 50
The Val Function
Val Function Value Returned
– Val("34.90") 34.9
– Val("86abc") 86
– Val("$24.95") 0
– Val("3,789") 3
– Val("") 0
– Val("x29") 0
– Val("47%") 47
– Val("Geraldine") 0
The ToString Method
•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 = 123lblNumber.text = number.ToString
Converts integer 123 to string “123” Then assigns the string to the text property of the lblNumber control
Formatting Numbers and Dates
ToString Argument
The ToString method may take a formatting argument, as shown in the table below.
Format String Description
N or n Number format
F or f Fixed-point scientific format
E or e Exponential scientific format
C or c Currency format
P or p Percent format
Example:strResult = dblSample.ToString("C")
Specifying Decimal Positions
• 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 2nd 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
.234 p 23.40 %
-1234567.8 c ($1,234,567.80)
Formatting Dates and Times
• The ToString method can format a Date or DateTime value in a variety of ways
• If the date is 4/7/2008 and the time is 3:22:18 PM
• Tutorial 3-8 provides an opportunity to work with number formatting concepts
Format String Description ToString() Value
d Short Date 4/7/2008
D Long Date Monday, April 7, 2008
t Short Time 3:22 PM
T Long Time 3:22:18 PM
F Full Date/Time
Monday, April 7, 2008 3:22:18 PM
Slide 3- 55
Exception Handling: Runtime Errors
• We’ve shown two possible runtime errors– DivideByZeroException– InvalidCastException– There are many others
• Runtime errors occur for may reasons • A runtime error results when:
– Visual Basic throws an exception– And it is an unhandled exception
• Exception handling allows a program to fail gracefully and recover if possible
Message Boxes• A message box is an easy way to notify the
user when an error occurs• MessageBox.Show displays a pop-up
window with a message and an OK button• There are two basic formats
MessageBox.Show( message )
MessageBox.Show( message, caption )• message appears in the body of the window• caption appears in the title bar of the window
Handling Exceptions
• Visual Basic provides an exception handler• A simple form that ignores some options is:
Trytry-block
Catch [exception-type]catch-block
End Try• The try-block contains program statements
that might throw an exception• The catch-block contains statements to
execute if an exception is thrown
Exception Handling Example
• Consider the following exception handling codeTryDim decSalary as DecimaldecSalary = CDec(txtSalary.Text)MessageBox.Show(“Your salary is “ _
& decSalary & “ dollars”)Catch
MessageBox.Show(“ Please try again,” _
& “and enter a number”, “Entry Error”)
End Try
• If CDec throws a cast exception, the try block catches it, jumps to and executes the catch block which displays the error message
Load Event Procedure
• Every form has a Load event procedure• Automatically executed when the form is
displayed• Double-click in any empty space on the form• The code window will appear• Place the code to be executed between the
Private Sub and End Sub lines
Debugging Problem
• The program runs but does not work correctly (has one or more logic errors)
• Running the program with various inputs has not isolated where those logic errors lie
• What can be done?
Visual Basic Debugging Aids
• You can set breakpoints– A line or lines you select in your source code– When execution reaches this line, it pauses– You may then examine the values in variables and
certain control properties– You may also single step through the program which
executes one statement at a time• This allows you to see and examine:
– What is happening one statement at a time– Where it is happening– What the various data values are (Watches)
Slide 3- 62
Visual Basic Debugging Aids
• Tutorial 3-12 demonstrates how to– Set breakpoints– Examine the values of variables and control
properties– Use the Autos,
Locals, and Watch windows
– Use the Debug ToolbarStart Debugging
Break All Stop Debugging
Step Into
Step Over
Step Out
Recommended