2002 prentice hall. all rights reserved. 1 outline 3.2simple program: printing a line of text...
TRANSCRIPT
2002 Prentice Hall. All rights reserved.
1
Outline3.2 Simple Program: Printing a Line of Text 3.3 Another Simple Program: Adding Integers 3.7 Using a Dialog to Display a Message
4.4 Control Structures 4.5 If/Then Selection Structure 4.6 If/Then/Else Selection Structure 5.5 Select Case Multiple-Selection Structure4.7 While Repetition Structure 4.8 Do While/Loop Repetition Structure 4.9 Do Until/Loop Repetition Structure 5.3 For/Next Repetition Structure5.6 Do/Loop While Repetition Structure5.7 Do/Loop Until Repetition Structure5.8 Using the Exit Keyword in a Repetition Structure
3.5 Arithmetic Operators 3.6 Equality and Relational Operators 4.10 Assignment Operators 5.9 Logical Operators
4.15 Introduction to Windows Application Programming
Introduction to Visual Basic .Net Programming, Control Structures and Operators
2002 Prentice Hall. All rights reserved.
2
3.2 Simple Program: Printing a Line of Text
• Simple console application that displays a line of text
• When the program is run– output appears in a command window
• It illustrates important Visual Basic features– Comments
– Modules
– Sub procedures
2002 Prentice Hall.All rights reserved.
Outline3
1 ' Fig. 3.1: Welcome1.vb2 ' Simple Visual Basic program.34 Module modFirstWelcome56 Sub Main()7 Console.WriteLine("Welcome to Visual Basic!")8 End Sub910 End Module
Welcome to Visual Basic!Single-quote character (') indicates that the remainder of the line is a comment
Visual Basic console applications consist of pieces called modules
The Main procedure is the entry point of the program. It is present in all console applications
The Console.WriteLine statement displays text output to the console
•A few Good Programming Practices
– Comments - Every program should begin with one or more comments
– Modules - Begin each module with mod to make modules easier to identify
– Procedures (subroutines) - Indent the entire body of each procedure definition one “level” of indentation
2002 Prentice Hall. All rights reserved.
4
3.2 Simple Program: Printing a Line of Text
• Now a short step-by-step explanation of how to create and run this program using the features of Visual Studio .NET IDE…
2002 Prentice Hall. All rights reserved.
5
3.2 Simple Program: Printing a Line of Text
1. Create the console application– Select File > New > Project…– In the left pane, select Visual Basic Projects– In the right pane, select Console Application– Name the project Welcome1– Specify the desired location
2. Change the name of the program file– Click Module1.vb in the Solution Explorer
window
– In the Properties window, change the File Name property to Welcome1.vb
2002 Prentice Hall. All rights reserved.
6
3.2 Simple Program: Printing a Line of Text
Fig. 3.2 Creating a Console Application with the New Project dialog.
Left pane Right pane
Project name
File location
2002 Prentice Hall. All rights reserved.
7
3.2 Simple Program: Printing a Line of Text
Fig. 3.3 IDE with an open console application.
Editor window (containing program code)
2002 Prentice Hall. All rights reserved.
8
3.2 Simple Program: Printing a Line of Text
Fig. 3.4 Renaming the program file in the Properties window.
Solution Explorer
File Name
property
Click Module1.vb to display its properties
Properties window
2002 Prentice Hall. All rights reserved.
9
3.2 Simple Program: Printing a Line of Text
3. Change the name of the module– Module names must be modified in the editor window
– Replace the identifier Module1 with modFirstWelcome
4. Writing code– Type the code contained in line 7 of Fig. 3.1 between Sub
Main() and End Sub• Note that after typing the class name and the dot operator the
IntelliSense is displayed. It lists a class’s members.
• Note that when typing the text between the parenthesis (parameter), the Parameter Info and Parameter List windows are displayed
2002 Prentice Hall. All rights reserved.
10
3.2 Simple Program: Printing a Line of Text
5. Run the program– To compile, select Build > Build Solution
• This creates a new file, named Welcome1.exe
– To run, select Debug > Start Without Debugging
2002 Prentice Hall. All rights reserved.
11
3.2 Simple Program: Printing a Line of Text
Fig. 3.5 IntelliSense feature of the Visual Studio .NET IDE.
Partially-typed member Member list
Description of highlighted member
2002 Prentice Hall. All rights reserved.
12
3.2 Simple Program: Printing a Line of Text
Fig. 3.6 Parameter Info and Parameter List windows.
Up arrow Down arrow
Parameter List window
Parameter Info window
2002 Prentice Hall. All rights reserved.
13
3.2 Simple Program: Printing a Line of Text
Fig. 3.7 Executing the program shown in Fig. 3.1.
Command window prompts the user to press a key after the program terminates
2002 Prentice Hall. All rights reserved.
14
3.2 Simple Program: Printing a Line of Text
Fig. 3.8 IDE indicating a syntax error.
Omitted parenthesis character (syntax error)
Blue underline indicates a
syntax error
Task List window
Error description(s)
2002 Prentice Hall.All rights reserved.
Outline15
1 ' Fig. 3.9: Welcome2.vb2 ' Writing line of text with multiple statements.34 Module modSecondWelcome56 Sub Main()7 Console.Write("Welcome to ")8 Console.WriteLine("Visual Basic!")9 End Sub ' Main1112 End Module ' modSecondWelcome
Welcome to Visual Basic!
Method Write does not position the output cursor at the beginning of the next line
Method WriteLine positions the output cursor at the beginning of the next line
2002 Prentice Hall. All rights reserved.
16
3.3 Another Simple Program: Adding Integers
• User input two integers– Whole numbers
• Program computes the sum• Display result
2002 Prentice Hall.All rights reserved.
Outline17
Addition.vb
1 ' Fig. 3.10: Addition.vb2 ' Addition program.3 4 Module modAddition5 6 Sub Main()7 8 ' variables for storing user input9 Dim firstNumber, secondNumber As String10 11 ' variables used in addition calculation12 Dim number1, number2, sumOfNumbers As Integer13 14 ' read first number from user15 Console.Write("Please enter the first integer: ")16 firstNumber = Console.ReadLine()17 18 ' read second number from user19 Console.Write("Please enter the second integer: ")20 secondNumber = Console.ReadLine()21 22 ' convert input values to Integers23 number1 = firstNumber24 number2 = secondNumber25 26 sumOfNumbers = number1 + number2 ' add numbers27 28 ' display results29 Console.WriteLine("The sum is {0}", sumOfNumbers)30 31 End Sub ' Main32 33 End Module ' modAddition
Variable declarations begin with keyword Dim
These variables store strings of characters
These variables store integers values
First value entered by user is assigned to variable firstNumber
Method ReadLine causes program to pause and wait for user input
Implicit conversion from String to Integer
Sums integers and assigns result to variable sumOfNumbers
Format indicates that the argument after the string will be evaluated and incorporated into the string
2002 Prentice Hall.All rights reserved.
Outline18
Please enter the first integer: 45Please enter the second integer: 72The sum is 117
Fig. 3.11 Dialog displaying a run-time error.
If the user types a non-integer value, such as “hello,” a run-time error occurs
2002 Prentice Hall. All rights reserved.
19
3.7 Using a Dialog to Display a Message
• Dialogs– Windows that typically display messages to the user
– Visual Basic provides class MessageBox for creating dialogs
2002 Prentice Hall.All rights reserved.
Outline20
SquareRoot.vb
Program Output
1 ' Fig. 3.20: SquareRoot.vb2 ' Displaying square root of 2 in dialog.34 Imports System.Windows.Forms ' Namespace containing MessageBox56 Module modSquareRoot78 Sub Main()910 ' Calculate square root of 211 Dim root As Double = Math.Sqrt(2)1213 ' Display results in dialog14 MessageBox.Show("The square root of 2 is " & root, _15 "The Square Root of 2")16 End Sub ' Main1718 End Module ' modThirdWelcome
Sqrt method of the Math class is called to compute the square root of 2
The Double data type stores floating-point numbers
Method Show of class MessageBox
Line-continuation character
Empty command window
2002 Prentice Hall. All rights reserved.
21
3.7 Using a Dialog to Display a Message
• Assembly– File that contain many classes provided by Visual Basic
– These files have a .dll (or dynamic link library) extension.
– Example• Class MessageBox is located in assembly System.Windows.Forms.dll
• MSDN Documentation– Information about the assembly that we need can be found in
the MSDN documentation
– Select Help > Index… to display the Index dialog
2002 Prentice Hall. All rights reserved.
22
3.7 Using a Dialog to Display a Message
Fig. 3.22 Obtaining documentation for a class by using the Index dialog.
Search string
Filter Link to MessageBox
documentation
2002 Prentice Hall. All rights reserved.
23
3.7 Using a Dialog to Display a Message
Fig. 3.23 Documentation for the MessageBox class.
Requirements section heading
MessageBox class documentation
Assembly containing class MessageBox
2002 Prentice Hall. All rights reserved.
24
3.7 Using a Dialog to Display a Message
• Reference– It is necessary to add a reference to the assembly if you wish
to use its classes
– Example• To use class MessageBox it is necessary to add a reference
to System.Windows.Forms
• Imports– Forgetting to add an Imports statement for a referenced
assembly is a syntax error
2002 Prentice Hall. All rights reserved.
25
3.7 Using a Dialog to Display a Message
Fig. 3.24 Adding a reference to an assembly in the Visual Studio .NET IDE.
References folder (expanded)
Solution Explorer before reference is added
Solution Explorer after reference is added
System.Windows.Forms reference
2002 Prentice Hall. All rights reserved.
26
3.7 Using a Dialog to Display a Message
Fig. 3.25 Internet Explorer window with GUI components.
LabelButton (displaying an icon)
Menu (e.g., Help) Text box
Menu bar
2002 Prentice Hall. All rights reserved.
27
4.4 Control Structures
• Transfer of control– GoTo statement
• It causes programs to become quite unstructured and hard to follow
• Bohm and Jacopini– All programs could be written in terms of three control
structures• Sequence structure
• Selection structure
• Repetition structure
2002 Prentice Hall. All rights reserved.
28
4.4 Control Structures
• Selection Structures– If/Then
• Single-selection structure
– If/Then/Else• Double-selection structure
– Select Case• Multiple-selection structure
2002 Prentice Hall. All rights reserved.
29
4.4 Control Structures
• Repetition Structures– While– Do While/Loop– Do/Loop While– Do Until/Loop– Do/Loop Until– For/Next– For Each/Next
2002 Prentice Hall. All rights reserved.
30
Visual Basic keywords
Visual Basic Keywords
AddHandler AddressOf Alias And
AndAlso Ansi As Assembly Auto Boolean ByRef Byte ByVal Call Case Catch CBool CByte CChar CDate CDec CDbl Char CInt Class CLng CObj Const CShort CSng CStr CType Date Decimal Declare Default Delegate Dim Do Double Each Else ElseIf End Enum Erase Error Event Exit ExternalSource False Finally For Friend Function Get GetType GoTo Handles If Implements Imports In Inherits Integer Interface Is Lib Like Long Loop Me Mod Module MustInherit MustOverride MyBase MyClass Namespace New Next Not Nothing NotInheritable NotOverridable Object On Option Optional Or OrElse Overloads Overridable Overrides ParamArray Preserve
2002 Prentice Hall. All rights reserved.
31
Visual Basic keywords
Private Property Protected Public RaiseEvent ReadOnly ReDim Region Rem RemoveHandler Resume Return Select Set Shadows Shared Short Single Static Step Stop String Structure Sub SyncLock Then Throw To True Try TypeOf Unicode Until When While With WithEvents WriteOnly Xor #Const #If...Then...#Else - -= &
&= * *= / /= \ \= ^ ^= + += = The following are retained as keywords, although they are no longer supported in Visual Basic.NET Let Variant Wend
Fig. 4.2 Visual Basic keywords.
2002 Prentice Hall. All rights reserved.
32
4.5 If/Then Selection Structure
• A selection structure chooses among alternative courses of action.
• It is a single-entry/single-exit structure• Example
If studentGrade >= 60 Then
Console.WriteLine("Passed")
End If
2002 Prentice Hall. All rights reserved.
33
4.6 If/Then/Else Selection Structure
• ExampleIf studentGrade >= 60 Then
Console.WriteLine("Passed")
Else
Console.WriteLine("Failed")
End If
2002 Prentice Hall. All rights reserved.
34
Nested If/Then/Else Selection Structure
• Test for multiple conditions by placing one structure inside the other.
• ElseIf keyword• Example
If studentGrade >= 60 Then
Console.WriteLine("Good")
ElseIf studentGrade >= 40
Console.WriteLine("Medium")
Else
Console.WriteLine("Bad")
End If
2002 Prentice Hall. All rights reserved.
35
5.5 Select Case Multiple-Selection Structure
• Multiple-Selection Structure– Tests expression separately for each value expression may
assume– Select Case keywords begin structure
• Followed by controlling expression– Compared sequentially with each case– Code in case executes if match is found– Program control proceeds to first statement after structure
• Case keyword– Specifies each value to test for– Followed by code to execute if test is true– Case Else
• Optional• Executes if no match is found• Must be last case in sequence
2002 Prentice Hall.All rights reserved.
Outline36
SelectTest.vb
1 ' Fig. 5.10: SelectTest.vb2 ' Using the Select Case structure.3 4 Module modEnterGrades5 6 Sub Main()7 Dim grade As Integer = 0 ' one grade8 Dim aCount As Integer = 0 ' number of As9 Dim bCount As Integer = 0 ' number of Bs10 Dim cCount As Integer = 0 ' number of Cs11 Dim dCount As Integer = 0 ' number of Ds12 Dim fCount As Integer = 0 ' number of Fs13 14 Console.Write("Enter a grade, -1 to quit: ")15 grade = Console.ReadLine()16 17 ' input and process grades18 While grade <> -119 20 Select Case grade ' check which grade was input21 22 Case 100 ' student scored 10023 Console.WriteLine("Perfect Score!" & vbCrLf & _24 "Letter grade: A" & vbCrLf)25 aCount += 126 27 Case 90 To 99 ' student scored 90-9928 Console.WriteLine("Letter Grade: A" & vbCrLf)29 aCount += 130 31 Case 80 To 89 ' student scored 80-8932 Console.WriteLine("Letter Grade: B" & vbCrLf)33 bCount += 134
Select Case begins multiple-selection structure
Controlling expressionFirst Case executes if grade is exactly 100
Next Case executes if grade is between 90 and 99, the range being specified with the To keyword
Identifier vbCrLf is the combination of the carriage return and linefeed characters
2002 Prentice Hall.All rights reserved.
Outline37
SelectTest.vb
35 Case 70 To 79 ' student scored 70-7936 Console.WriteLine("Letter Grade: C" & vbCrLf)37 cCount += 138 39 Case 60 To 69 ' student scored 60-6940 Console.WriteLine("Letter Grade: D" & vbCrLf)41 dCount += 142 43 ' student scored 0 or 10-59 (10 points for attendance)44 Case 0, 10 To 5945 Console.WriteLine("Letter Grade: F" & vbCrLf)46 fCount += 147 48 Case Else49 50 ' alert user that invalid grade was entered51 Console.WriteLine("Invalid Input. " & _52 "Please enter a valid grade." & vbCrLf)53 End Select54 55 Console.Write("Enter a grade, -1 to quit: ")56 grade = Console.ReadLine()57 End While58 59 ' display count of each letter grade60 Console.WriteLine(vbCrLf & _61 "Totals for each letter grade are: " & vbCrLf & _62 "A: " & aCount & vbCrLf & "B: " & bCount _63 & vbCrLf & "C: " & cCount & vbCrLf & "D: " & _64 dCount & vbCrLf & "F: " & fCount)65 66 End Sub ' Main67 68 End Module ' modEnterGrades
Optional Case Else executes if no match occurs with previous Cases
End Select marks end of structure
2002 Prentice Hall.All rights reserved.
Outline38
Program Output
Enter a grade: 84Letter Grade: B Enter a grade: 100Perfect Score!Letter grade : A+ Enter a grade: 7Invalid Input. Please enter a valid grade. Enter a grade: 95Letter Grade: A Enter a grade: 78Letter Grade: C Totals for each letter grade are:A: 2B: 1C: 1D: 0F: 0
2002 Prentice Hall. All rights reserved.
39
4.7 While Repetition Structure
• Executes an action while the condition is true• Example
' writes numbers from 1 to 10Dim number As Integer = 1While number <= 10
Console.Write("{0} ", number)number = number + 1
End While
2002 Prentice Hall. All rights reserved.
40
4.8 Do While/Loop Repetition Structure
• Behaves like the While repetition structure• Example
' writes numbers from 1 to 10Dim number As Integer = 1Do While number <= 10
Console.Write("{0} ", number)number = number + 1
Loop
2002 Prentice Hall. All rights reserved.
41
4.9 Do Until/Loop Repetition Structure
• Executes an action until a condition is false• Example
' writes numbers from 1 to 10Dim number As Integer = 1Do Until number > 10
Console.Write("{0} ", number)number = number + 1
Loop
2002 Prentice Hall. All rights reserved.
42
5.6 Do/Loop While Repetition Structure
• Do/Loop While Repetition Structure– Similar to While and Do/While– Loop-continuation condition tested after body executes
• Loop body always executed at least once
– Begins with keyword Do– Ends with keywords Loop While followed by condition
• Example ' writes numbers from 1 to 10Dim number As Integer = 1Do
Console.Write("{0} ", number)number = number + 1
Loop While (number <= 10)
2002 Prentice Hall. All rights reserved.
43
5.7 Do/Loop Until Repetition Structure
• Do/Loop Until Repetition Structure– Similar to Do Until/Loop structure
– Loop-continuation condition tested after body executes• Loop body always executed at least once
• Example ' writes numbers from 1 to 10Dim number As Integer = 1Do
Console.Write("{0} ", number)number = number + 1
Loop Until number > 10
2002 Prentice Hall. All rights reserved.
44
5.3 For/Next Repetition Structure
• For/Next counter-controlled repetition– Structure header initializes control variable, specifies final
value and increment• For keyword begins structure
– Followed by control variable initialization• To keyword specifies final value• Step keyword specifies increment
– Optional
– Increment defaults to 1 if omitted
– May be positive or negative
– Next keyword marks end of structure
– Executes until control variable greater (or less) than final value
2002 Prentice Hall. All rights reserved.
45
5.3 For/Next Repetition Structure
• Example' writes numbers from 1 to 10Dim number As Integer For counter = 1 To 10 Step 1
Console.Write("{0} ", number)Next
2002 Prentice Hall. All rights reserved.
46
5.4 Examples Using the For/Next Structure
• Examples– Vary the control variable from 1 to 100 in increments of 1
• For i = 1 To 100 • For i = 1 To 100 Step 1
– Vary the control variable from 100 to 1 in increments of –1• For i = 100 To 1 Step –1
– Vary the control variable from 7 to 77 in increments of 7• For i = 7 To 77 Step 7
– Vary the control variable from 20 to 2 in increments of –2• For i = 20 To 2 Step -2
2002 Prentice Hall.All rights reserved.
Outline47
Sum.vb
Program Output
1 ' Fig. 5.5: Sum.vb2 ' Using For/Next structure to demonstrate summation.3 4 Imports System.Windows.Forms5 6 Module modSum7 8 Sub Main()9 10 Dim sum = 0, number As Integer11 12 ' add even numbers from 2 to 10013 For number = 2 To 100 Step 214 sum += number15 Next16 17 MessageBox.Show("The sum is " & sum, _18 "Sum even integers from 2 to 100", _19 MessageBoxButtons.OK, MessageBoxIcon.Information)20 End Sub ' Main21 22 End Module ' modSum
Control variable counts by 2, from 2 to 100
Value of number is added in each iteration to determine sum of even numbers
Text displayed in dialogDisplay a MessageBox
Indicate button to be OK button
Indicate icon to be Information icon
Text displayed in title bar
2002 Prentice Hall. All rights reserved.
48
5.4 Examples Using the For/Next Structure
MessageBoxIcon Constants Icon Description
MessageBoxIcon.Exclamation Icon containing an exclamation point. Typically used to caution the user against potential problems.
MessageBoxIcon.Information Icon containing the letter "i." Typically used to display information about the state of the application.
MessageBoxIcon.Question Icon containing a question mark. Typically used to ask the user a question.
MessageBoxIcon.Error Icon containing an in a red circle. Typically used to alert the user of errors or critical situations.
Fig. 5.6 Icons for message dialogs.
2002 Prentice Hall. All rights reserved.
49
5.4 Examples Using the For/Next Structure
MessageBoxButton constants Description
MessageBoxButton.OK OK button. Allows the user to acknowledge a message. Included by default.
MessageBoxButton.OKCancel OK and Cancel buttons. Allow the user to either continue or cancel an operation.
MessageBoxButton.YesNo Yes and No buttons. Allow the user to respond to a question
MessageBoxButton.YesNoCancel Yes, No and Cancel buttons. Allow the user to respond to a question or cancel an operation.
MessageBoxButton.RetryCancel Retry and Cancel buttons. Typically used to allow the user to either retry or cancel an operation that has failed.
MessageBoxButton.AbortRetry- Ignore
Abort, Retry and Ignore buttons. When one of a series of operations has failed, these butons allow the user to abort the entire sequence, retry the failed operation or ignore the failed operation and continue..
Fig. 5.7 Button constants for message dialogs.
Fig. 5.7 Button constants for message dialogs.
2002 Prentice Hall.All rights reserved.
Outline50
Interest.vb
1 ' Fig. 5.8: Interest.vb2 ' Calculating compound interest.3 4 Imports System.Windows.Forms5 6 Module modInterest7 8 Sub Main()9 10 Dim amount, principal As Decimal ' dollar amounts11 Dim rate As Double ' interest rate12 Dim year As Integer ' year counter13 Dim output As String ' amount after each year14 15 principal = 1000.0016 rate = 0.0517 18 output = "Year" & vbTab & "Amount on deposit" & vbCrLf19 20 ' calculate amount after each year21 For year = 1 To 1022 amount = principal * (1 + rate) ^ year23 output &= year & vbTab & _24 String.Format("{0:C}", amount) & vbCrLf25 Next26 27 ' display output28 MessageBox.Show(output, "Compound Interest", _29 MessageBoxButtons.Ok, MessageBoxIcon.Information)30 31 End Sub ' Main32 33 End Module ' modInterest
Perform calculation to determine amount in account
Append year followed by the formatted calculation result and newline character to end of String output
Specify C (for “currency”) as formatting code
Type Decimal used for precise monetary calculations
2002 Prentice Hall.All rights reserved.
Outline51
Program Output
2002 Prentice Hall. All rights reserved.
52
5.4 Examples Using the For/Next Structure
Format Code Description C Currency. Precedes the number with $, separates every three digits
with commas and sets the number of decimal places to two.
E Scientific notation. Displays one digit to the left of the decimal and six digits to the right of the decimal, followed by the character E and a three-digit integer representing the exponent of a power of 10. For example, 956.2 is formatted a 9.562000E+002..
F Fixed point. Sets the number of decimal places to two.
G General. Visual Basic chooses either E or F for you, depending on which representation generates a shorter string.
D Decimal. Displays an integer as a whole number in standard base-10 format.
N Number. Separates every three digits with a comma and sets the number of decimal places to two.
X Hexadecimal integer. Displays the integer in hexadecimal (base-16) notation. We discuss hexidecimal notation in Appendix B.
Fig. 5.9 String formatting codes.
Fig. 5.9 String formatting codes.
2002 Prentice Hall. All rights reserved.
53
5.8 Using the Exit Keyword in a Repetition Structure
• Exit Statements– Alter the flow of control
• Cause immediate exit from a repetition structure
– Exit Do• Executed in Do structures
– Exit For• Executed in For structures
– Exit While• Executed in While structures
2002 Prentice Hall.All rights reserved.
Outline54
ExitTest.vb
1 ' Fig. 5.16: ExitTest.vb2 ' Using the Exit keyword in repetition structures.3 4 Imports System.Windows.Forms5 6 Module modExitTest7 8 Sub Main()9 Dim output As String10 Dim counter As Integer11 12 For counter = 1 To 1013 14 ' skip remaining code in loop only if counter = 315 If counter = 3 Then16 Exit For17 End If18 19 Next20 21 output = "counter = " & counter & _22 " after exiting For/Next structure" & vbCrLf23 24 Do Until counter > 1025 26 ' skip remaining code in loop only if counter = 527 If counter = 5 Then28 Exit Do29 End If30 31 counter += 132 Loop33
Loop specified to execute 10 timesExit For statement
executes when condition is met, causing loop to exit
Program control proceeds to first statement after the structure
counter is 3 when loop starts, specified to execute until it is greater than 10
Exit Do executes when counter is 5, causing loop to exit
2002 Prentice Hall.All rights reserved.
Outline55
Program Output
34 output &= "counter = " & counter & _35 " after exiting Do Until/Loop structure" & vbCrLf36 37 While counter <= 1038 39 ' skip remaining code in loop only if counter = 740 If counter = 7 Then41 Exit While42 End If43 44 counter += 145 End While46 47 output &= "counter = " & counter & _48 " after exiting While structure"49 50 MessageBox.Show(output, "Exit Test", _51 MessageBoxButtons.OK, MessageBoxIcon.Information)52 End Sub ' Main53 54 End Module ' modExitTest
counter is 5 when loop starts, specified to execute while less than or equal to 10
Exit While executes when counter is 7, causing loop to exit
2002 Prentice Hall. All rights reserved.
56
3.5 Arithmetic Operators
2002 Prentice Hall. All rights reserved.
57
3.6 Equality and Relational Operators
Standard algebraic equality operator or relational operator
Visual Basic equality or relational operator
Example of Visual Basic condition
Meaning of Visual Basic condition
Equality operators
= x = y x is equal to y
<> x <> y x is not equal to y
Relational operators
> > x > y x is greater than y
< < x < y x is less than y
>= x >= y x is greater than or equal to y
? <= x <= y x is less than or equal to y
Fig. 3.17 Equality and relational operators.
2002 Prentice Hall. All rights reserved.
58
4.10 Assignment Operators
• Binary operators– +, -, *, ^, &, / or \
variable = variable operator expression
variable operator= expression
• Example– Addition assignment operator, +=
value = value + 3
value += 3
2002 Prentice Hall. All rights reserved.
59
4.10 Assignment Operators
Assignment operator Sample expression Explanation Assigns
Assume: c = 4, d =
"He"
+= c += 7 c = c + 7 11 to c -= c -= 3 c = c - 3 1 to c *= c *= 4 c = c * 4 16 to c /= c /= 2 c = c / 2 2 to c \= c \= 3 c = c \ 3 1 to c ^= c ^= 2 c = c ^ 2 16 to c &= d &= "llo" d = d & "llo" "Hello" to d Fig. 4.11 Assignment operators.
Fig. 4.11 Assignment operators.
2002 Prentice Hall. All rights reserved.
60
5.9 Logical Operators
• Used to form complex conditions by combining simple ones– Short-circuit evaluation
• Execute only until truth or falsity is known
– AndAlso operator• Returns true if and only if both conditions are true
– OrElse operator• Returns true if either or both of two conditions are true
2002 Prentice Hall. All rights reserved.
61
5.9 Logical Operators (II)
• Logical Operators without short-circuit evaluation– And and Or
• Similar to AndAlso and OrElse respectively
• Always execute both of their operands
• Used when an operand has a side effect
– Condition makes a modification to a variable
– Should be avoided to reduce subtle errors
– Xor• Returns true if and only if one operand is true and the other
false
2002 Prentice Hall. All rights reserved.
62
5.9 Logical Operators (III)
• Logical Negation– Not
• Used to reverse the meaning of a condition
• Unary operator
– Requires one operand
• Can usually be avoided by expressing a condition differently
2002 Prentice Hall. All rights reserved.
63
5.9 Logical Operators
expression1 expression2 expression1 AndAlso expression2
False False False
False True False True False False True True True Fig. 5.17 Truth table for the AndAlso (logical AND) operator.
expression1 expression2 expression1 OrElse expression2
False False False
False True True True False True True True True Fig. 5.18 Truth table for the OrElse (logical OR) operator.
2002 Prentice Hall. All rights reserved.
64
5.9 Logical Operators
expression1 expression2 expression1 Xor expression2
False False False
False True True True False True True True False Fig. 5.19 Truth table for the boolean logical exclusive OR (Xor) operator.
expression Not expression
False True
True False Fig. 5.20 Truth table for operator Not (logical NOT).
2002 Prentice Hall. All rights reserved.
65
Precedence and Associativity of Operators
Operators Associativity Type () left to right parentheses
^ left to right exponentiation
+ - left to right unary prefix
* / left to right multiplicative
\ left to right Integer division
Mod left to right modulus
+ - left to right additive
& left to right concatenation
< <= > >= = <> left to right relational and equality
Not left to right logical NOT
And AndAlso left to right boolean logical AND
Or OrElse left to right boolean logical inclusive OR
Xor left to right boolean logical exclusive OR
Fig. 5.22 Precedence and associativity of the operators discussed so far.
lower precedence
higher precedence
2002 Prentice Hall. All rights reserved.
66
4.15 Introduction to Windows Application Programming
• Windows application– Consists of at least one class
• Inherits from class Form• Form is called the superclass or base class
– Keyword Class• Begins a class definition and is followed by the class name
– Keyword Inherits• Indicates that the class inherits existing pieces from another
class
2002 Prentice Hall. All rights reserved.
67
4.15 Introduction to Windows Application Programming
Fig. 4.21 IDE showing program code for Fig. 2.15.
Collapsed code
2002 Prentice Hall. All rights reserved.
68
4.15 Introduction to Windows Application Programming
• Windows Form Designer generated code– Collapsed by default
– The code is created by the IDE and normally is not edited by the programmer
– Present in every Windows application
2002 Prentice Hall. All rights reserved.
69
4.15 Introduction to Windows Application Programming
Fig. 4.22 Windows Form Designer generated code when expanded.
Expanded code
2002 Prentice Hall. All rights reserved.
70
4.15 Introduction to Windows Application Programming
Fig. 4.23 Code generated by the IDE for lblWelcome.
Click here for code view
Click here for design view
Property initializations for lblWelcome
2002 Prentice Hall. All rights reserved.
71
4.15 Introduction to Windows Application Programming
• How IDE updates the generated code1. Modify the file name
• Change the name of the file to ASimpleProgram.vb
2. Modify the label control’s Text property using the Properties window• Change the property of the label to “Deitel and
Associates”
3. Examine the changes in the code view• Switch to code view and examine the code
4. Modifying a property value in code view• Change the string assigned to Me.lblWelcome.Text to
“Visual Basic .NET”
2002 Prentice Hall. All rights reserved.
72
4.15 Introduction to Windows Application Programming
Fig. 4.24 Using the Properties window to set a property value.
Text property
2002 Prentice Hall. All rights reserved.
73
4.15 Introduction to Windows Application Programming
Fig. 4.25 Windows Form Designer generated code reflecting new property values.
Text property
2002 Prentice Hall. All rights reserved.
74
4.15 Introduction to Windows Application Programming
Fig. 4.26 Changing a property in the code view editor.
Text property
2002 Prentice Hall. All rights reserved.
75
4.15 Introduction to Windows Application Programming
Fig. 4.27 New Text property value reflected in design mode.
Text property value
2002 Prentice Hall. All rights reserved.
76
4.15 Introduction to Windows Application Programming
5. Change the label’s Text Property at runtime• Add a method named FrmASimpleProgram_Load to the
class
• Add the statement lblWelcome.Text = "Visual Basic" in the body of the method definition
6. Examine the results of the FrmASimpleProgram_Load method• Select Build > Build Solution then Debug > Start
2002 Prentice Hall. All rights reserved.
77
4.15 Introduction to Windows Application Programming
Fig. 4.28 Adding program code to FrmASimpleProgram_Load.
FrmASimpleProgram_Load method
2002 Prentice Hall. All rights reserved.
78
4.15 Introduction to Windows Application Programming
Fig. 4.29 Method FrmASimpleProgram_Load containing program code.