Learning Loops in VB.NET for Game Development - Do...Loop
(Page 3 of 4 )
The Do ...Loop statement offers another loop that we can use, the Do loop. It's similar to While ...End , but it's more complex, supporting a variety of behaviors. In its most basic form, it's not any different from an infinite While loop, except we're able to omit the expression altogether. Here's a new version of our input-echoing loop, rewritten using Do ...Loop:
Dim input As String
Do
input = Console.ReadLine()
Console.WriteLine(input)
Loop
If we want to terminate the loop, we have to do so manually by using Exit, as we did earlier with the infinite While loop, since we didn't provide an expression. However, we must specify that we're exiting a Do loop instead of a While loop. Here, we exit if the user types “quit”:
Dim input As String
Do
input = Console.ReadLine()
Console.WriteLine(input)
If input.ToLower() = "quit" Then
Exit Do
End If
Loop
The real value in the Do loop, however, lies in its support for multiple behaviors. The loop supports two basic modes of behavior: While and Until . We can either tell our loop to run while a condition is true, or we can tell our loop to do something until a condition is true. Let's take these two behaviors one at a time, starting with the While behavior. Let's create a loop that will echo user input as long as (while) the user does not type “quit”:
Dim input As String = ""
Do While input.ToLower() <> "quit"
input = Console.ReadLine()
Console.WriteLine(input)
Loop
As before, we must assign a value to input. Actually, as you've probably noticed, the above loop bears a strong resemblance to our earlier While loop. Hold that thought for just a moment while we move on to the second mode of behavior, Until. Let's recreate our loop to echo user input until the user types “quit”:
Dim input As String = ""
Do Until input.ToLower() = "quit"
input = Console.ReadLine()
Console.WriteLine(input)
Loop
Though the above two loops function the exact same way, the expressions used are opposites. In effect, Do Until operates while the expression comes out False . Then, when it comes out True, the loop terminates. Sometimes, this mode of behavior is more straightforward and readable. In fact, it suits our example quite well.
Next: Do...Loop continued >>
More Visual Basic.NET Articles
More By Peyton McCullough