The syntax for the first ver-sion of the Do...Whileloop is as follows: Do While condition statements Loop Conditionis expressed in the form of an expression, like this: intCounter = 0 Do
Trang 1The Do Whilestatement creates a loop that runs as long as a specified condition is true VBScript supports two different versions of the Do Whileloop The syntax for the first ver-sion of the Do Whileloop is as follows:
Do While condition
statements
Loop
Conditionis expressed in the form of an expression, like this:
intCounter = 0
Do While intCounter < 10
intCounter = intCounter + 2
Loop
In this example, the expression (intCounter < 10) allows the loop to continue as long as the value of intCounter is less than 10 The value of intCounter is initially set to 0, but is increased by 2every time the loop executes As a result, the loop iterates five times
As the Whilekeyword has been placed at the beginning of the loop, the loop will not execute
if the value of counter is already 10 or greater
The syntax for the second format of the Do Whilestatement is as follows:
Do
statements
Loop While condition
As you can see, the While keyword had been moved from the beginning to the end of the loop Therefore, the loop will always execute at least once, even if the condition is initially false
Let’s look at another example of the Do While loop in action In this example, the Do Whileloop is set up to collect names and phone numbers for an address book The loop uses the VBScript InputBox()function to collect the names and phone numbers The names and addresses are added to a variable string and formatted such that, when displayed, each entry is listed on a separate line The user may enter as many names and numbers as he or she wishes When done adding new address book entries, all he or she must do is type “Quit”
as the final entry
Dim intCounter, strAddressBook, strAddressEntry
intCounter = 0
Trang 2Do While strAddressEntry <> “Quit”
intCounter = intCounter + 1
strAddressEntry = InputBox(“Please type a name, a space, and then “ & _
“the person’s phone number”, “Personal Address Book”)
If strAddressEntry <> “Quit” Then
strAddressBook = strAddressBook & strAddressEntry & vbCrLf
End If
Loop
MsgBox strAddressBook, ,”New Address Book Entries = “ & intCounter – 1
Figure 6.9 displays a list of four names entered as this script executed
Alternatively, you could have written this example as shown next In this example the While keyword and its associated condition have been moved to the end of the loop However, the script still operates exactly as in the previous example
Dim intCounter, strAddressBook, strAddressEntry
intCounter = 0
Do
intCounter = intCounter + 1
strAddressEntry = InputBox(“Please type a name, a space, and then “ & _
“the person’s phone number”, “Personal Address Book”) If strAddressEntry <>
“Quit” Then
strAddressBook = strAddressBook & strAddressEntry & vbCrLf
End If
Loop While strAddressEntry <> “Quit”
MsgBox strAddressBook, ,”New Address Book Entries = “ & intCounter –1
Figure 6.9
Using a
Do While loop
to collect new
address book
entries.
Trang 3One of the dangers of working with loops is that you may accidentally create a loop that has
no way of terminating its own execution This is an endless loop Endless loops run forever, needlessly consuming computer resources and degrading a computer’s performance For example, look at the following:
intCounter = 0
Do While intCounter < 10
intCounter = intCounter + 1
WScript.Echo intCounter
Loop
When executed this script counts from 1 to 10 Now look at the next script
intCounter = 0
Do While intCounter < 10
intCounter = intCounter - 1
WScript.Echo intCounter
Loop
It looks almost exactly like the previous example, only instead of incrementing the value of intCounterby 1, it increments the value of intCounterby –1, creating an endless loop One way to protect against the creation of an endless loop is to put in a safety net, like this: intCounter = 0
Do While intCounter < 10
intCounter = intCounter – 1
intNoExecutions = intNoExecutions + 1
WScript.Echo intCounter
If intNoExecutions > 99 Then
Exit Do
End If
Loop
As you can see, I added to the script a variable called intNoExecutions that I then used to keep track of the number of times that loop iterated If the loop iterates 100 times, then something is wrong So I added an Ifstatement to test the value of intNoExecutionseach time the loop is processed and to execute the Exit Dostatement in the event that something goes wrong Of course, there is no substitute for good program design and careful testing
Trang 4The VBScript Do Untilstatement creates a loop that executes as long as a condition is false (that is, until it becomes true) VBScript supports two versions of the Do Untilstatement The syntax for the first version is as follows:
Do Until condition
statements
Loop
Let’s look at an example that demonstrates how this loop works In this example, shown next, the script prompts the player to answer a question and uses a Do Untilloop to allow the user up to three chances to correctly answer the question
Dim intMissedGuesses, strPlayerAnswer
intMissedGuesses = 1
Do Until intMissedGuesses > 3
strPlayerAnswer = InputBox(“Where does Peter Pan live?”)
If strPlayerAnswer <> “Neverland” Then
intMissedGuesses = intMissedGuesses + 1
If intMissedGuesses < 4 Then
MsgBox “Incorrect: You have “ & 4 – intMissedGuesses & _
“ guesses left Please try again.”
Else
MsgBox “Sorry You have used up all your chances.”
End If
Else
intMissedGuesses = 4
MsgBox “Correct! I guess that you must believe in Faith, Trust “ & _
“and Pixy Dust!”
End If
Loop
Trang 5In this example, the loop has been set up to execute until the value of a variable named intMissedGuessesbecomes greater than 3 The variable is initially set equal to 1 and is incre-mented by 1 each time the loop executes, unless the player provides a correct answer, in which case the script sets the value of intMissedGuessesto 4 in order to arbitrarily terminate the loop’s execution
Figure 6.10 demonstrates the execution of this script by showing the pop-up dialog that appears if the player guesses incorrectly on his or her first attempt to answer the question
The syntax of the second form of the Do Untilstatement is as follows:
Do
statements
Loop Until condition
As you can see, the Untilkeyword and its associated conditionhave been moved from the beginning to the end of the loop, thus ensuring the loop executes at least once
While…Wend
The While Wendstatement creates a loop that executes as long as a tested condition is true The syntax for this loop is as follows:
While condition
statements
Wend
The Do While and Do Until loops provide the same functionality as the While Wend loop The general rule of thumb, therefore, is that you should use one of the Do loops in place of this statement However, I’d be remiss if I failed to show you how this statement works, so take a look at the following example:
Dim intCounter, strCountList
Figure 6.10
Using a
Do Until
loop to provide
the player with
three chances to
correctly answer
a question.
Trang 6intCounter = 0
While intCounter < 10
intCounter = intCounter + 1
strCountList = strCountList & intCounter & vbCrLf
Wend
MsgBox “This is how to count to 10:” & vbCrLf & vbCrLf & _
strCountList, , “Counting Example”
This example begins by initializing two variables intCountis used to control the loop’s exe-cution strCountListis used to build a formatted script containing the numbers counted by the script The loop itself iterates 10 times Figure 6.11 shows the output created by this example when run using the WScript execution host
Back to the Guess a Number Game
Let’s turn our attention back to the Guess a Number game In this game, the player is prompted to guess a randomly generated number between 1 and 100 Each time the player takes a guess, the script will check to see if the correct number was guessed If not, the script will provide a hint to help the player on his or her next guess
Developing this script will enhance your knowledge and understanding of working with the Do Until loop You will also work with the Ifstatement, and learn how to work with a number of new built-in VBScript functions
Designing the Game
The Guess a Number game begins by asking the player to guess a number between 1 and 100, and then helps the user guess the number by providing hints This project has five steps
Figure 6.11
Counting to
10 using a
While End
loop.
Trang 7These steps are
1 Add the standard documentation template and define any variables, constants, or objects used by the script
2 Generate a random number between 1 and 100
3 Create a loop that runs until the player either guesses the correct answer or gives up
4 Test the player’s answer to see whether it’s valid
5 Test the player’s answer to see whether it is too low, too high, or correct
As a kind of project bonus, once you have completed the Guess a Number game, I’ll show you how to create a VBScript desktop shortcut for it I’ll also show you how to use shortcuts
to configure the Windows Start Menu and Quick Launch toolbar
Beginning the Guess a Number Game
Begin by creating a new script and adding your script template
‘*************************************************************************
‘Script Name: GuessANumber.vbs
‘Author: Jerry Ford
‘Created: 10/19/02
‘Description: This script plays a number-guessing game with the user
‘*************************************************************************
‘Initialization Section
Option Explicit
Next, create a constant and assign it the text message to be used in the title bar of the script’s pop-up dialogs
Const cGreetingMsg = “Pick a number between 1 – 100”
Define four variables as shown Use intUserNumber to store the player’s numeric guess intRandomNo stores the script’s randomly generated number strOkToEnd is a variable the script uses to determine whether the game should be stopped, and intNoGuesseskeeps track
of the number of guesses the player makes
Dim intUserNumber, intRandomNo, strOkToEnd, intNoGuesses
Finally, set the initial value of intNoGuessesto 0, like this:
intNoGuesses = 0
Trang 8Generating the Game’s Random Number
The following statements are next and are responsible for generating the game’s random number:
‘Generate a random number
Randomize
intRandomNo = FormatNumber(Int((100 * Rnd) + 1))
The Randomize statement ensures that a random number is generated each time the game
is played The last statement uses the following built-in VBScript functions to generate a number between 1 and 100
• Rnd() Returns a randomly generated number.
• Int() Returns the integer portion of a number.
• FormatNumber() Returns an expression that has been formatted as a number.
Creating a Loop to Control the Game
Now you’ll need to set up the Do Until loop that controls the game’s execution In this example, the loop executes until the value assigned to the strOkToEndvariable is set to yes
Do Until strOkToEnd = “yes”
‘Prompt users to pick a number
intUserNumber = InputBox(“Type your guess:”,cGreetingMsg)
intNoGuesses = intNoGuesses + 1
.
.
.
Loop
As you can see, the only statement inside the loop, for now, prompts the player to guess a number and keeps track of the number of guesses made by the player
Testing Player Input
Now let’s put together the code that performs validation of the data supplied by the player
‘See if the user provided an answer
If Len(intUserNumber) <> 0 Then
‘Make sure that the player typed a number
If IsNumeric(intUserNumber) = True Then
Trang 9.
.
Else
MsgBox “Sorry You did not enter a number Try again.”, , cGreetingMsg
End If
Else
MsgBox “You either failed to type a value or you clicked on Cancel “ & _
“Please play again soon!”, , cGreetingMsg
strOkToEnd = “yes”
End If
The first validation test is performed using the built-in VBScript Len()function It is used to ensure that the player actually typed in a number before clicking on the OKbutton If the player’s input is not 0characters long, the game continues to the next test Otherwise, an error message is displayed, and the value of strOkToEnd is set to yes, terminating the loop and ending the game If the length test is passed, then the script performs a second valida-tion test on the player’s input This time, the built-in VBScript IsNumeric()function is used
to make sure that the player typed a number instead of a letter or other special character If
a number was typed, then the game continues If a number was not typed, then an error message is displayed, but the game continues with the next iteration of the loop
Determine Whether the Player’s Guess Is High, Low, or Correct
There are three more sets of statements that need to be added to the script They will be inserted one after another, just after the Ifstatement that performs the game’s second val-idation test
The first of these three sets of statements is shown here It begins by verifying that the user’s guess matches the game’s randomly selected number Then it displays a message congratu-lating the player, showing the random number, and showing the number of guesses that it took for the player to guess it Finally, the value of strOkToEnd is set equal to yes This ter-minates the loop and allows the game to end
‘Test to see if the user’s guess was correct
If FormatNumber(intUserNumber) = intRandomNo Then
MsgBox “Congratulations! You guessed it The number was “ & _
intUserNumber & “.” & vbCrLf & vbCrLf & “You guessed it “ & _
“in “ & intNoGuesses & “ guesses.”, ,cGreetingMsg
strOkToEnd = “yes”
End If
Trang 10The second of the three sets of statements provides the player with help if his or her guess
is too low The value of strOkToEndis set equal to no This ensures that the loop that controls the game will continue
‘Test to see if the user’s guess was too low
If FormatNumber(intUserNumber) < intRandomNo Then
MsgBox “Your guess was too low Try again”, ,cGreetingMsg
strOkToEnd = “no”
End If
Finally, the last collection of statements provides the player with help if his or her guess is too high The value of strOkToEndis set equal to no This ensures that the loop that controls the game will continue
‘Test to see if the user’s guess was too high
If FormatNumber(intUserNumber) > intRandomNo Then
MsgBox “Your guess was too high Try again”, ,cGreetingMsg
strOkToEnd = “no”
End If
The Final Result
Let’s put all the pieces of the Guess a Number script together and see how it looks fully laid out
‘*************************************************************************
‘Script Name: GuessANumber.vbs
‘Author: Jerry Ford
‘Created: 10/19/02
‘Description: This script plays a number-guessing game with the user
‘*************************************************************************
‘Initialization Section
Option Explicit
Const cGreetingMsg = “Pick a number between 1 - 100”
Dim intUserNumber, intRandomNo, strOkToEnd, intNoGuesses
intNoGuesses = 0