0% found this document useful (0 votes)
4 views

VBHTP2e_03-Beta

This document serves as an introduction to Visual Basic programming, outlining objectives such as writing simple programs, using data types, and performing calculations. It includes sections on creating console applications, displaying text, and handling user input, along with examples and best practices for coding. The document also emphasizes the importance of readability and error prevention in programming.

Uploaded by

abdallahm.alsoud
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

VBHTP2e_03-Beta

This document serves as an introduction to Visual Basic programming, outlining objectives such as writing simple programs, using data types, and performing calculations. It includes sections on creating console applications, displaying text, and handling user input, along with examples and best practices for coding. The document also emphasizes the importance of readability and error prevention in programming.

Uploaded by

abdallahm.alsoud
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 96

1

3
Introduction to
Visual Basic
Programming

 2007 Pearson Education, Inc. All rights reserved.


2

Comment is free, but facts are sacred.


—C. P. Scott

When faced with a decision, I always ask, “What


would be the most fun?”
—Peggy Walker

Equality, in a social sense, may be divided into that


of condition and that of rights.
—James Fenimore Coope

 2007 Pearson Education, Inc. All rights reserved.


3

OBJECTIVES
In this chapter you will learn:
 To write simple Visual Basic programs using code rather
than visual programming.
 To write statements that input data from the keyboard and
output data to the screen.
 To declare and use data of various types.
 To store and retrieve data from memory.
 To use arithmetic operators to perform calculations.
 To use the precedence of arithmetic operators to determine
the order in which operators are applied.
 To write decision-making statements.
 To use equality and relational operators to compare
operands.
 To use message dialogs to display messages.

 2007 Pearson Education, Inc. All rights reserved.


4

3.1 Introduction
3.2 Displaying a Line of Text
3.3 Creating Your First Console Application in Visual
Basic Express
3.4 Displaying a Single Line of Text with Multiple
Statements
3.5 Adding Integers
3.6 Memory Concepts
3.7 Arithmetic
3.8 Decision Making: Equality and Relational Operators
3.9 Using a Message Dialog to Display a Message
3.10 (Optional) Software Engineering Case Study:
Examining the ATM Requirements Document
3.11 Wrap-Up
3.12 Web Resources

 2007 Pearson Education, Inc. All rights reserved.


5

3.1 Introduction

• Console Application
– Input and output text in console window
• Windows 95/98/ME: MS-DOS prompt
• Other version of Windows: Command Prompt

 2007 Pearson Education, Inc. All rights reserved.


6

3.2 Displaying a Line of Text

• Sample program
– Displays a line of text
– Illustrates several important VB language features

 2007 Pearson Education, Inc. All rights reserved.


1 ' Fig. 3.1: Welcome1.vb 7
2 ' Simple Visual Basic program.
Outline
3
4 Module FirstWelcome
5
6 Sub Main() Entry point of program Welcome1.vb
7
8 Console.WriteLine("Welcome to Visual Basic!") Console.WriteLine
9 outputs to screen
10 End Sub ' Main End subroutine Main
11
12 End Module ' FirstWelcome

Welcome to Visual Basic!

 2007 Pearson Education,


Inc. All rights reserved.
8

3.2 Displaying a Line of Text (Cont.)

1 ‘ Fig. 3.1: Welcome1.vb

2 ‘ Simple Visual Basic program.

– Comments start with: ‘


• Comments ignored during program execution
• Document and describe code
• Provides code readability

 2007 Pearson Education, Inc. All rights reserved.


9

3.2 Displaying a Line of Text (Cont.)

• Blank line
– Makes program more readable
– Blank lines, spaces, and tabs are white-space characters
– Ignored by compiler

4 Module FirstWelcome

• Module declaration for module Welcome1


– Modules are logical grouping of methods that simplify program organization
– Keyword: words reserved for use by Visual Basic
• Module keyword followed by module name
- Must have corresponding End Module statement
– Naming classes: capitalize every word (Pascal casting)
• SampleClassName

 2007 Pearson Education, Inc. All rights reserved.


10

Visual Basic keywords

AddHandler AddressOf Alias And


AndAlso Ansi As Assembly
Auto Boolean ByRef Byte
ByVal Call Case Catch
CBool CByte CChar CDate
CDbl CDec Char CInt
Class CLng CObj Const
Continue CSByte CShort CSng
CStr CType CUInt CULng
CUShort Date Decimal Declare
Default Delegate Dim DirectCast
Do Double Each Else
ElseIf End Enum Erase
Error Event Exit False

Fig. 3.2 | Keywords in Visual Basic. (Part 1 of 3.)

 2007 Pearson Education, Inc. All rights reserved.


11

Visual Basic keywords

Finally For Friend Function


Get GetType Global GoTo
Handles If Implements Imports
In Inherits Integer Interface
Is IsNot Lib Like
Long Loop Me Mod
Module MustInherit MustOverride MyBase
MyClass Namespace Narrowing New
Next Not Nothing NotInheritable
NotOverridable Object Of On
Operator Option Optional Or
OrElse Overloads Overridable Overrides
ParamArray Partial Preserve Private
Property Protected Public RaiseEvent

Fig. 3.2 | Keywords in Visual Basic. (Part 2 of 3.)

 2007 Pearson Education, Inc. All rights reserved.


12

Visual Basic keywords

ReadOnly ReDim REM RemoveHandler


Resume Return SByte Select
Set Shadows Shared Short
Single Static Step Stop
String Structure Sub SyncLock
Then Throw To True
Try TryCast TypeOf UInteger
ULong Unicode Until UShort
Using When While Widening
With WithEvents WriteOnly Xor

The following are retained as keywords, although they are no longer supported in Visual
Basic 2005
EndIf GoSub Let Variant Wend

Fig. 3.2 | Keywords in Visual Basic. (Part 3 of 3.)

 2007 Pearson Education, Inc. All rights reserved.


13

3.2 Displaying a Line of Text (Cont.)

– Visual Basic identifier


• Series of characters consisting of letters, digits and
underscores ( _ )
• Does not begin with a digit, has no spaces
• Examples: Welcome1, identifier, _value, button7
- 7button is invalid
• VB is not case sensitive (capitalization does not matters)
- a1 and A1 are the same

 2007 Pearson Education, Inc. All rights reserved.


14

Common Programming Error 3.1

Identifiers cannot be keywords, so it is an error,


for example, to choose any of the words in Fig. 3.2
as a Module name. The Visual Basic compiler
helps you locate such errors in your programs.
Though keywords cannot be used as identifiers,
they can be used in strings and comments.

 2007 Pearson Education, Inc. All rights reserved.


15

Good Programming Practice 3.1

Use whitespace to enhance program readability.

 2007 Pearson Education, Inc. All rights reserved.


16

3.2 Displaying a Line of Text (Cont.)

6 Sub Main()

– Part of every Visual Basic application


• Applications begin executing at Main
- Sub indicates that Main is a method
- VB applications contain one or more methods
• Exactly one method must be called Main
– Methods can perform tasks and return information
• Sub means Main returns no information
- Abbreviation for subroutine
- Must have corresponding End Sub statement

 2007 Pearson Education, Inc. All rights reserved.


17

Good Programming Practice 3.2

Indent the entire body of each method declaration


one additional “level” of indentation. This
emphasizes the structure of the method,
improving its readability. In this text, one level
of indentation is set to three spaces—this keeps
the code readable yet concise.

 2007 Pearson Education, Inc. All rights reserved.


18

3.2 Displaying a Line of Text (Cont.)

– Instructs computer to perform an action


• Prints string of characters
- String: series characters inside double quotes
• White-spaces in strings are not ignored by compiler
– Method Console.WriteLine
• Standard output
• Print to command window (i.e., MS-DOS prompt)
• Displays line of text

 2007 Pearson Education, Inc. All rights reserved.


19

3.3 Creating Your First Console


Application in Visual Basic Express
• Creating the Console Application
– Open New Project dialog and select Console
Application (Fig. 3.3-3.4)
• Modifying the Editor Settings to Display Line Numbers
– Visual Basic Express provides many ways to personalize your
coding experience (Fig. 3.5)
• Changing the Name of the Program File
– Change the File Name property in the Solution Explorer
(Fig. 3.6)
• Setting the Startup Object
– Each Visual Basic project has a startup object that specifies
where the application begins executing. (Fig. 3.7)

 2007 Pearson Education, Inc. All rights reserved.


20

Fig. 3.3 | Creating a Console Application with the New Project dialog.

 2007 Pearson Education, Inc. All rights reserved.


21

Fig. 3.4 | IDE with an open console application.

 2007 Pearson Education, Inc. All rights reserved.


22

Fig. 3.5 | Modifying the IDE settings.

 2007 Pearson Education, Inc. All rights reserved.


23

Fig. 3.6 | Renaming the program file in the Properties window.

 2007 Pearson Education, Inc. All rights reserved.


24

Fig. 3.7 | Setting the startup object.

 2007 Pearson Education, Inc. All rights reserved.


25
3.3 Creating Your First Console
Application in Visual Basic Express
(Cont.)
• Writing Code
– IntelliSense: Lists a class’s members after a dot (Fig. 3.8-3.9)
• Saving the Application
– Specify the directory where you want to save the project (Fig.
3.10)
• Compiling and Running the Application (Fig. 3.11)
– Compiler compiles code into files
• Ex: .exe (executable), .dll (dynamic link library), and more!
• Running the Application from the Command Prompt
– Alternate way to go run a program without using the IDE (Fig.
3.12-3.13)

 2007 Pearson Education, Inc. All rights reserved.


26

Fig. 3.8 | IntelliSense feature of Visual Basic Express.

 2007 Pearson Education, Inc. All rights reserved.


27

Fig. 3.9 | Parameter Info window.

 2007 Pearson Education, Inc. All rights reserved.


28

Fig. 3.10 | Save Project dialog.

 2007 Pearson Education, Inc. All rights reserved.


29

Fig. 3.11 | Executing the program shown in Fig. 3.1.

 2007 Pearson Education, Inc. All rights reserved.


30

Fig. 3.12 | Executing the program shown in Fig. 3.1 from a Command Prompt.

 2007 Pearson Education, Inc. All rights reserved.


31

Fig. 3.13 | Executing the program shown in Fig. 3.1 from a Command Prompt.

 2007 Pearson Education, Inc. All rights reserved.


32
3.3 Creating Your First Console
Application in Visual Basic Express
(Cont.)
• Syntax Errors, Error Messages and the Error
List Window
– Syntax Error
• A violation of Visual Basic rules for creating correct application

– Error List Window (Fig. 3.14)


• Window where the descriptions of the errors are located

Note: Red underline indicts a syntax error

 2007 Pearson Education, Inc. All rights reserved.


33

Error-Prevention Tip 3.1

One syntax error can lead to multiple entries in


the Error List window. Each error that you
address could eliminate several subsequent error
messages when you recompile your program. So,
when you see a particular error you know how to
fix, correct it and recompile—this may make the
other errors disappear.

 2007 Pearson Education, Inc. All rights reserved.


34

Fig. 3.14 | Syntax error indicated by the IDE.

 2007 Pearson Education, Inc. All rights reserved.


35

3.4 Displaying a Single Line of Text with


Multiple Statements
• Modified program
– SecondWelcome.cs (Fig. 3.15) produces same output as
FirstWelcome.cs (Fig. 3.1)
– Using different code
8 Console.Write( "Welcome to ");
9 Console.WriteLine( “Visual Basic!" );

– Line 7 displays “Welcome to ” with cursor remaining on


printed line
– Line 8 displays “Visual Basic! ” on same line with cursor
on next line

 2007 Pearson Education, Inc. All rights reserved.


1 ' Fig. 3.15: Welcome2.vb 36
2 ' Displaying a line of text with multiple statements.
Outline
3
4 Module SecondWelcome
5
6 Sub Main() Welcome2.vb
7
8 Console.Write("Welcome to ") Cursor stays on same line after outputting
9 Console.WriteLine("Visual Basic!")
10
11 End Sub ' Main Cursor moves to next line after outputting
12
13 End Module ' SecondWelcome

Welcome to Visual Basic!

 2007 Pearson Education,


Inc. All rights reserved.
37

3.5 Adding Integers

• Variables
– Location in memory that stores a value
• Declare with name and type before use
– In most cases, uses keyword Dim when declaring variables
– Variable name: any valid identifier
• Initialize variable in its declaration
– Equal sign

 2007 Pearson Education, Inc. All rights reserved.


1 ' Fig. 3.16: Addition.vb 38
2 ' Addition program.
3
Outline
4 Module Addition
5
6 Sub Main()
7 Addition.vb
8 ' variables used in the addition calculation
9 Dim number1 As Integer
10 Dim number2 As Integer Declare variables number1,
11 Dim total As Integer number2 and sum.
12
13 ' prompt for and read the first number from the user
14 Console.Write("Please enter the first integer: ")
15 number1 = Console.ReadLine() Assign user’s input to number1.
16
17 ' prompt for and read the second number from the user
18 Console.Write("Please enter the second integer: ")
19 number2 = Console.ReadLine()
Assign user’s input to number2.
20
21 total = number1 + number2 ' add the numbers
22
23 Console.WriteLine("The sum is " & total) ' display the sum
24
25 End Sub ' Main Calculate the sum of the
26 variables number1 and
27 End Module ' Addition number2, assign result to sum.
Please enter the first integer: 45
Please enter the second integer: 72
The sum is 117

Display the sum.


 2007 Pearson Education,
Inc. All rights reserved.
39

3.5 Adding Integers (Cont.)


9 Dim number1 As Integer

10 Dim number2 As Integer

11 Dim sum As Integer

– Declare variable number1, number2 and sum of


type Integer
• Integer holds integer values (whole numbers): i.e., 0, -4, 97
• Types Single, Double and Decimal can hold decimal
numbers
• Type Char can hold a single character, i.e.: x, $, 7
• Integer, Float, Double, Decimal and Char are primitive
types

– Can declare multiple variables of the same type in one


declaration
• Use comma-separated list

 2007 Pearson Education, Inc. All rights reserved.


40

3.5 Adding Integers (Cont.)


14 Console.Write( "Enter first integer: " )

– Message called a prompt: directs user to perform an action


15 number1 = Console.ReadLine()

– ReadLine waits for user to type a string of characters


– Result of call to ReadLine given to number1 using assignment
operator =
• = is a binary operator
- Takes two operands
• Expression on right evaluated and assigned to variable on
left
• Read as: number1 gets the value of Console.ReadLine()

 2007 Pearson Education, Inc. All rights reserved.


41

3.5 Adding Integers (Cont.)


18 Console.Write( "Enter second integer: " )

– Similar to previous statement


• Prompts the user to input the second integer
19 number2 = Console.ReadLine()

– Similar to previous statement


• Assign variable number2 to second integer input
21 sum = number1 + number2 ‘ add the numbers

– Assignment statement
• Calculates sum of number1 and number2 (right hand side)
• Uses assignment operator = to assign result to variable sum
• Read as: sum gets the value of number1 + number2
• number1 and number2 are operands

 2007 Pearson Education, Inc. All rights reserved.


42

3.5 Adding Integers (Cont.)


23 Console.WriteLine( “The sum is : " & sum ) ‘ display the sum

– Use Console.WriteLine to display results


– & is the string concatenation operator

Console.WriteLine( "Sum is {0} " & ( number1 + number2 ) );

– Calculations can also be performed inside WriteLine


– Parentheses around the expression number1 + number2
are not required

 2007 Pearson Education, Inc. All rights reserved.


43

Primitive Types

Boolean Byte Char


Date Decimal Double
Integer Long SByte
Short Single String
UInteger ULong UShort

Fig. 3.17 | Primitive types in Visual Basic.

 2007 Pearson Education, Inc. All rights reserved.


44

Good Programming Practice 3.3

Choosing meaningful variable names helps a


program to be “self-documenting” (i.e., the
program can be understood by others without
the use of documentation manuals or excessive
comments).

 2007 Pearson Education, Inc. All rights reserved.


45

Good Programming Practice 3.4

A common convention (and the one used in this book) is


to have the first word in a variable-name identifier begin with a
lowercase letter. Every word in the name after the first word should
begin with a uppercase letter. For example, identifier firstNumber
has a capital N beginning its second word, Number. We use a similar
convention for module names, except that the first letter
of the first word is also capitalized. Although identifiers are not case
sensitive, using these conventions helps make your programs more
readable. In this book, we use widely adopted Visual Basic naming
conventions.

 2007 Pearson Education, Inc. All rights reserved.


46

Good Programming Practice 3.5

Declaring each variable on a separate line allows


for easy insertion of an end-of-line comment next
to each declaration. We will follow this
convention.

 2007 Pearson Education, Inc. All rights reserved.


47

Good Programming Practice 3.6

Place spaces on either side of a binary operator


to make the operator stand out and improve the
readability of the statement.

 2007 Pearson Education, Inc. All rights reserved.


48

Fig. 3.18 | Dialog displaying a run-time error.

 2007 Pearson Education, Inc. All rights reserved.


49

Good Programming Practice 3.7

Follow a method’s End Sub with an end-of-line


comment containing the name of the method that
the End Sub terminates.

 2007 Pearson Education, Inc. All rights reserved.


50

3.6 Memory Concepts

• Variables
– Every variable has a name, a type, a size and a value
• Name corresponds to location in memory
– When new value is placed into a variable, replaces (and
destroys) previous value
– Reading variables from memory does not change them

 2007 Pearson Education, Inc. All rights reserved.


51

Fig. 3.19 | Memory location showing name and value of variable number1.

 2007 Pearson Education, Inc. All rights reserved.


52

Fig. 3.20 | Memory locations after values for variables number1 and number2
have been input.

 2007 Pearson Education, Inc. All rights reserved.


53

Fig. 3.21 | Memory locations after an addition operation.

 2007 Pearson Education, Inc. All rights reserved.


54

3.7 Arithmetic

• Arithmetic calculations used in most programs


– Usage
• * for multiplication
• \ for integer division
- Any fractional part is truncated
• / for floating-point division
• Mod for modulus
• +, -
– Integer division truncates remainder
7 \ 5 evaluates to 1
– Remainder operator Mod returns the remainder
7 Mod 5 evaluates to 2

 2007 Pearson Education, Inc. All rights reserved.


55

Arithmetic Algebraic Visual Basic


Visual Basic operation
operator expression expression

Addition + f+7 f + 7
Subtraction – p–c p - c

Multiplication * bm b * m

x
/ x y or or x÷y x / y
Division (floating point) y

Division (integer) \ none v \ u

Modulus Mod r mod s r Mod s

Exponentiation ^ qp q ^ p

Unary minus - –e –e

Unary plus + +g +g

Fig. 3.22 | Arithmetic operators.

 2007 Pearson Education, Inc. All rights reserved.


56

3.7 Arithmetic (Cont.)

• Operator precedence
– Some arithmetic operators act before others (i.e.,
multiplication before addition)
• Use parenthesis when needed or for clarity
– Example: Find the average of three variables a, b and c
• Do not use: a + b + c / 3
• Use: ( a + b + c ) / 3

 2007 Pearson Education, Inc. All rights reserved.


57

Common Programming Error 3.2

Using the integer division operator (\) when the


floating-point division operator (/) is expected
(i.e., when one or both of the operands is a
floating-point value) can lead to incorrect results.

 2007 Pearson Education, Inc. All rights reserved.


58

Error-Prevention Tip 3.2

Ensure that each integer division operator has


only integer operands.

 2007 Pearson Education, Inc. All rights reserved.


59

Operator(s) Operation Order of evaluation (precedence)

^ Exponentiation Evaluated first. If there are several such


operators, they are evaluated from left to right.
+, – Sign operations Evaluated second. If there are several such
operators, they are ev aluated from left to right.
*, / Multiplication Evaluated third. If there are several such
and Division operators, they are evaluated from left to right.
\ Integer Evaluated fourth. If there are several such
division operators, they are evaluated from left to right.
Mod Modulus Evaluated fifth. If there are several such
operators, they are evaluated from left to right.
+, – Addition and Evaluated sixth. If there are several such
Subtraction operators, they are evaluated from left to right.

Fig. 3.23 | Precedence of arithmetic operators.

 2007 Pearson Education, Inc. All rights reserved.


60

Good Programming Practice 3.8

Redundant parentheses can make complex


expressions easier to read.

 2007 Pearson Education, Inc. All rights reserved.


61

Error-Prevention Tip 3.3

When you are uncertain about the order of


evaluation in a complex expression, use
parentheses to force the order, as you would
do in an algebraic expression. Doing so can help
avoid subtle bugs.

 2007 Pearson Education, Inc. All rights reserved.


62

Fig. 3.24 | Order in which a second-degree polynomial is evaluated.

 2007 Pearson Education, Inc. All rights reserved.


63

3.8 Decision Making: Equality and


Relational Operators
• Condition
– Expression can be either True or False
• If…Then statement
– Simple version in this section, more detail later
– If a condition is True, then the body of the If…Then
statement executed
– Control always resumes after the If…Then statement
– Conditions in If…Then statements can be formed using
equality or relational operators (Fig. 3.25)

 2007 Pearson Education, Inc. All rights reserved.


64

Standard algebraic Visual Basic Example of


Meaning of Visual Basic
equality operator or equality or Visual Basic
condition
relational operator relational operator 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.25 | Equality and relational operators.

 2007 Pearson Education, Inc. All rights reserved.


65

Common Programming Error 3.3

It is a syntax error to reverse the symbols in the


operators <>, >= and <= (as in ><, =>, =<).

 2007 Pearson Education, Inc. All rights reserved.


1 ' Fig. 3.26: Comparison.vb 66
2 ' Using equality and relational operators.
Outline
3
4 Module Comparison
5
6 Sub Main() Comparison.vb
7
8 ' declare Integer variables for user input (1 of 3 )
9 Dim number1 As Integer
10 Dim number2 As Integer
11
12 ' read first number from user
13 Console.Write("Please enter first integer: ")
14 number1 = Console.ReadLine()
15
16 ' read second number from user
17 Console.Write("Please enter second integer: ")
18 number2 = Console.ReadLine()
19

 2007 Pearson Education,


Inc. All rights reserved.
20 If number1 = number2 Then ' number1 is equal to number2 67
21 Console.WriteLine(number1 & " = " & number2)
Outline
Test for equality, display
22 End If
23
result using WriteLine.
24 If number1 <> number2 Then ' number1 is not equal to number2
25 Console.WriteLine(number1 & " <> " & number2) Comparison.vb
26 End If
Compares two numbers
27 (2 of 3 )
28 If number1 < number2 Then ' number1 is less than number2 using relational operator <.
29 Console.WriteLine(number1 & " < " & number2)
30 End If
31
32 If number1 > number2 Then ' number1 is greater than number2
33 Console.WriteLine(number1 & " > " & number2)
34 End If
35
36 ' number1 is less than or equal to number2 Compares two numbers
37 If number1 <= number2 Then using relational operators >
38 Console.WriteLine(number1 & " <= " & number2) and <=.
39 End If
40

 2007 Pearson Education,


Inc. All rights reserved.
41 ' number1 is greater than or equal to number2 68
42 If number1 >= number2 Then
Outline
43 Console.WriteLine(number1 & " >= " & number2)
44 End If
45
46 End Sub ' Main
Compares two numbers
Comparison.vb
47 using relational operator <.
48 End Module ' Comparison (3 of 3 )
Please enter first integer: 1000
Please enter second integer: 2000
1000 <> 2000
1000 < 2000
1000 <= 2000

Please enter first integer: 515


Please enter second integer: 49
515 <> 49
515 > 49
515 >= 49

Please enter first integer: 333


Please enter second integer: 333
333 = 333
333 <= 333
333 >= 333

 2007 Pearson Education,


Inc. All rights reserved.
69

3.8 Decision Making: Equality and


Relational Operators (Cont.)
– Line 4: begins module Comparison declaration
– Lines 9-10: declare Integers variables
– Lines 13-14: prompt the user to enter the first integer and
input the value
– Lines 17-18: prompt the user to enter the second integer
and input the value

 2007 Pearson Education, Inc. All rights reserved.


70

3.8 Decision Making: Equality and


Relational Operators (Cont.)
20 If number1 = number2 Then ‘ number1 is equal to number2

21 Console.WriteLine( number1 & “ = ” & number2 )


22 End If
– If…Then statement to test for equality using (=)
• If variables equal (condition true)
- Line 21 executes
• If variables not equal, statement skipped
• Empty statement
- No task is performed
– Lines 24-26, 28-30, 32-34, 37-39 and 42-44
• Compare number1 and number2 with the operators <>, <,
>, <= and >=, respectively

 2007 Pearson Education, Inc. All rights reserved.


71

Good Programming Practice 3.9

Indent the statement in the body of an If...


Then statement to emphasize the body statement
and enhance program readability.

 2007 Pearson Education, Inc. All rights reserved.


72

Operators Type

^ exponentiation
+ - sign operations (unary)
* / multiplication and floating-point division
\ Integer division
Mod modulus
+ - addition and subtraction (binary)
= <> < <= > >= equality and relational

Fig. 3.27 | Precedence of the operators introduced in this chapter.

 2007 Pearson Education, Inc. All rights reserved.


1 ' Fig. 3.28: SquareRoot.vb 73
2 ' Displaying the square root of 2 in a dialog.
3
Outline
4 Imports System.Windows.Forms ' Namespace containing class MessageBox
5
6 Module SquareRoot
7 Assign the square SquareRoot.vb
8 Sub Main() root of 2 to root
9
10 Dim root As Double = Math.Sqrt(2) ' calculate the square root of 2
11
12 ' display the results in a message dialog
13 MessageBox.Show("The square root of 2 is " & root, _
14 "The Square Root of 2")
15
16 End Sub ' Main
17
Show results via a
18 End Module ' SquareRoot message dialog

 2007 Pearson Education,


Inc. All rights reserved.
74

3.9 Using a Message Dialog to Display a


Message
• Message Dialogs
– Windows that display messages to the user
– Class MessageBox
• System.Windows.Forms
- Classes that help programmers define GUIs for their
application

• FCL classes are grouped by functionality into namespaces


– Some classes need to be added to the project before use; located
in an assembly
• Add Reference
• Imports statement indicates which namespace to use
– The IDE will implicitly add various references depending on the
type of a project.

 2007 Pearson Education, Inc. All rights reserved.


75

3.9 Using a Message Dialog to Display a


Message (Cont.)
• Line continuation
– Any statement in Visual Basic can be written as more than
a line
– Use the character “_”
• One whitespace character must precede the character

 2007 Pearson Education, Inc. All rights reserved.


76

Common Programming Error 3.4

Splitting a statement over several lines without


including the line-continuation character is a
syntax error.

 2007 Pearson Education, Inc. All rights reserved.


77

Common Programming Error 3.5

Failure to precede the line-continuation character


(_) with at least one whitespace character is a
syntax error.

 2007 Pearson Education, Inc. All rights reserved.


78

Common Programming Error 3.6

Placing anything, including comments, on the


same line after a line-continuation character is
a syntax error.

 2007 Pearson Education, Inc. All rights reserved.


79

Common Programming Error 3.7

Splitting a statement in the middle of an identifier


or string is a syntax error.

 2007 Pearson Education, Inc. All rights reserved.


80

Good Programming Practice 3.10

If a single statement must be split across lines,


choose breaking points that make sense, such as
after a comma in a comma-separated list or after
an operator in a lengthy expression. If a statement
is split across two or more lines, indent all
subsequent lines with one level of indentation.

 2007 Pearson Education, Inc. All rights reserved.


81

Good Programming Practice 3.11

Place a space after each comma in a method’s


argument list to make method calls more
readable.

 2007 Pearson Education, Inc. All rights reserved.


82

Fig. 3.29 | Message dialog displayed by calling MessageBox.Show.

 2007 Pearson Education, Inc. All rights reserved.


83

Fig. 3.30 | Obtaining documentation for a class by using the Index dialog.

 2007 Pearson Education, Inc. All rights reserved.


84

Fig. 3.31 | Documentation for the MessageBox class.

 2007 Pearson Education, Inc. All rights reserved.


85

Common Programming Error 3.8

Including a namespace with the Imports


statement without adding a reference to the
proper assembly results in a compilation error.

 2007 Pearson Education, Inc. All rights reserved.


86

Fig. 3.32 | Viewing a project’s references.

 2007 Pearson Education, Inc. All rights reserved.


87

Fig. 3.33 | Adding an assembly reference to a project in the Visual Basic 2005 Express IDE.

 2007 Pearson Education, Inc. All rights reserved.


88

3.10 (Optional) Software Engineering Case


Study: Examining the Requirements Document

• Object-oriented design (OOD) process using


UML
– Chapters 4 to 9, 11
• Object-oriented programming (OOP)
implementation
– Appendix J

 2007 Pearson Education, Inc. All rights reserved.


89

Fig. 3.34 | Internet Explorer window with GUI components.

 2007 Pearson Education, Inc. All rights reserved.


90

Fig. 3.35 | Automated teller machine user interface.

 2007 Pearson Education, Inc. All rights reserved.


91

Fig. 3.36 | ATM main menu.

 2007 Pearson Education, Inc. All rights reserved.


92

Fig. 3.37 | ATM withdrawal menu.

 2007 Pearson Education, Inc. All rights reserved.


93

3.10 (Optional) Software Engineering Case


Study: Examining the Requirements Document
(Cont.)
• Analyzing the ATM System
– Requirements gathering
– Software life cycle
• Waterfall model: Perform each stage once in succession
• Iterative model: Repeat one or more stages several times
– Use case modeling
• Use Case Diagram
– Model the interactions between clients and its use cases
– Actor
• External entity

 2007 Pearson Education, Inc. All rights reserved.


94

Fig. 3.38 | Use case diagram for the ATM system from the user’s perspective.

 2007 Pearson Education, Inc. All rights reserved.


95

Fig. 3.39 | Use case diagram for a modified version of our ATM system that also allows
users to transfer money between accounts.

 2007 Pearson Education, Inc. All rights reserved.


96

3.10 (Optional) Software Engineering Case


Study: Examining the Requirements Document
(Cont.)
• UML diagram types (UML 2 specifies 13 diagram types)
– Model system structure and behavior
• Use case diagrams
- Model interactions between user and a system
• Class diagram
- Models classes, or “building blocks” of a system
• State machine diagrams
- Model the ways in which an object changes state
• Activity diagrams
- Models an object’s activity during program execution
• Communication diagrams (collaboration diagrams)
- Models the interactions among objects
- Emphasize what interactions occur
• Sequence diagrams
- Models the interactions among objects
- Emphasize when interactions occur

 2007 Pearson Education, Inc. All rights reserved.

You might also like