Microsoft Visual Basic 2010 Step by Step eBook

(Tina Meador) #1

Chapter 7 Using Loops and Timers 193


Note The previous code samples asked the user to type Done to quit. Note that the test of the
entered text is case-sensitive, which means that typing done or DONE doesn’t end the program.
You can make the test case-insensitive by using the StrComp function, which I’ll discuss in
Chapter 13, “Exploring Text Files and String Processing .”

Avoiding an Endless Loop


Because of the relentless nature of Do loops, it’s very important to design your test
conditions so that each loop has a true exit point. If a loop test never evaluates to False,
the loop executes endlessly, and your program might not respond to input. Consider the
following example:

Dim Number as Double
Do
Number = InputBox("Enter a number to square. Type –1 to quit.")
Number = Number * Number
TextBox1.Text = Number
Loop While Number >= 0

In this loop, the user enters number after number, and the program squares each number
and displays it in the text box. Unfortunately, when the user has had enough, he or she
can’t quit because the advertised exit condition doesn’t work. When the user enters –1, the
program squares it, and the Number variable is assigned the value 1. (The problem can be
fixed by setting a different exit condition. The next example demonstrates how to check
if the user clicked the Cancel button and exited the loop .) Watching for endless loops is
essential when you’re writing Do loops. Fortunately, they’re pretty easy to spot if you test
your programs thoroughly.

Important Be sure that each loop has a legitimate exit condition.

The following exercise shows how you can use a Do loop to convert Fahrenheit temperatures
to Celsius temperatures. The simple program prompts the user for input by using the
InputBox function, converts the temperature, and displays the output in a message box.

Convert temperatures by using a Do loop


  1. On the File menu, click New Project.


The New Project dialog box opens.


  1. Create a new Visual Basic Windows Forms Application project named My Celsius
    Conversion.

Free download pdf