Section 3.2. Displaying a Line of Text


3.2. Displaying a Line of Text

We begin by considering a simple program (Fig. 3.1) that displays a line of text. When this program runs, its output appears in a Command Prompt window. We show such output in a blue box following the program listing. You will see what a Command Prompt window looks like later in this section, when we explain the process of creating a console application.

Figure 3.1. Simple Visual Basic program.

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

 Welcome to Visual Basic! 



Analyzing the Program

This program illustrates several important Visual Basic features. For your convenience, all program listings in this text include line numbersthese are not part of the Visual Basic language. The line numbers help us refer to specific parts of a program. We will soon show how to display line numbers in program files. Each program is followed by one or more windows showing the program's execution output.

Line 1 of Fig. 3.1 begins with a single-quote character (') which indicates that the remainder of the line is a comment. Programmers insert comments in programs to improve the readability of the codeyou can write anything you want in a comment. Comments can be placed either on their own lines (we call these "full-line comments") or at the end of a line of Visual Basic code (we call these "end-of-line comments"). The Visual Basic compiler ignores commentsthey do not cause the computer to perform any actions when you run a program. The comment in line 1 simply indicates the figure number (Fig. 3.1) and the file name (Welcome1.vb) in which we stored this program. The comment in line 2 provides a brief description of the program. By convention, we begin every program in this manner (you can, of course, say anything you want in a comment).

Visual Basic console applications consist of pieces called modules, which are logical groupings of methods that simplify program organization. Lines 412 define our first module. These lines collectively are called a module declaration. We discuss the method in lines 610 momentarilymethods perform tasks and can return information when the tasks are completed. Every console application in Visual Basic consists of at least one module and one method in that module. In Chapter 7, Methods: A Deeper Look, we discuss methods in detail.

The word Module (line 4) is an example of a keyword. Keywords are words reserved for use by Visual Basic. A complete list of Visual Basic keywords is presented in Fig. 3.2. We discuss many of Visual Basic's keywords throughout this book. Visual Basic has a larger set of keywords than most other programming languages.

Figure 3.2. Keywords in Visual Basic.

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

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

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


The name of the ModuleFirstWelcome in line 4is known as an identifier, which is a series of characters consisting of letters, digits and underscores (_). Identifiers cannot begin with a digit and cannot contain spaces. Examples of valid identifiers are value1, FirstWelcome, xy_coordinate, _total and grossPay. The name 7Welcome is not a valid identifier because it begins with a digit, and the name input field is not a valid identifier because it contains a space.

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. Though keywords cannot be used as identifiers, they can be used in strings and comments.


Visual Basic keywords and identifiers are not case sensitiveuppercase and lowercase letters are considered to be identical, which causes firstwelcome and FirstWelcome to be interpreted as the same identifier. Although keywords appear to be case sensitive, they are not. Visual Basic Express applies its "preferred" case (i.e., the casing used in Fig. 3.2) to each letter of a keyword, so when you type module and press the Enter key, Visual Basic changes the lowercase m to uppercase, as in Module, even though module would be perfectly correct.

Lines 3, 5, 7, 9 and 11 (Fig. 3.1) are blank lines. Blank lines, space characters and tab characters are used throughout a program to make it easier to read. Collectively, these are called whitespace characters.

Line 6 is present in all Visual Basic console applications. These begin executing at Main, which is known as the entry point of the program. The keyword Sub that appears before Main indicates that Main is a method.

Note that lines 610 are indented three spaces relative to lines 4 and 12. Indentation improves program readability. We refer to spacing conventions that enhance program clarity as Good Programming Practices. We show how to set the indent size in Visual Basic Express shortly.

The keyword Sub (line 6) begins the body of the method declaration. The keywords End Sub (line 10) close the method declaration's body. The keyword Sub is short for "subroutine"an early term for method. Note that the line of code (line 8) in the method body is indented three additional spaces to the right relative to lines 6 and 10. This emphasizes that line 8 is part of the Main method's body.

Good Programming Practice 3.1

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 spacesthis keeps the code readable yet concise.


Using Console.WriteLine to Display Text

Line 8 in Fig. 3.1 does the "real work" of the program, displaying the phrase Welcome to Visual Basic! on the screen. Characters and the surrounding double quotes are called strings, character strings or string literals.

The entire line, including Console.WriteLine and its string in the parentheses, is called a statement. When this statement executes, it displays (or prints) the message Welcome to Visual Basic! in the Console window (Fig. 3.1).

Note that Console.WriteLine contains two identifiers (i.e., Console and WriteLine) separated by the dot separator (.). The identifier to the right of the dot separator is the method name, and the identifier to the left of the dot separator is the class name to which the method belongs. Classes organize groups of related methods and data; methods perform tasks and can return information when the tasks are completed. For instance, the Console class contains methods, such as WriteLine, that communicate with users via the Console window. The statement in line 8 is a method callit invokes method WriteLine of class Console. In Fig. 3.1, the string in parentheses in line 8 is the argument to method WriteLine.

When method WriteLine completes its task, it positions the output cursor at the beginning of the next line in the Console window. Program execution terminates when the program encounters the keywords End Sub in line 10. The Module is a package that contains the program's methods; the methods contain the statements that perform the actions of the program.



Visual BasicR 2005 for Programmers. DeitelR Developer Series
Visual Basic 2005 for Programmers (2nd Edition)
ISBN: 013225140X
EAN: 2147483647
Year: 2004
Pages: 435

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net