Learning Loops in VB.NET for Game Development - While...End continued
(Page 2 of 4 )
The code in the previous section will accept user input, echo the input, and then stop as soon as it encounters the Exit statement. Typically, though, we'll want to attach some sort of condition to our Exit statement (otherwise, why use a loop?). For example, we can choose to exit the loop only if the user types “quit”:
Dim input As String
While True
input = Console.ReadLine()
Console.WriteLine(input)
If input.ToLower() = "quit" Then
Exit While
End If
End While
If the user types “quit,” then we exit. We convert the input to lower case in order to get around case sensitivity. That way, the user can type “QUIT,” “QuIt,” etc., and the effect will be the same. In any case, the above code is bad. We evaluate an expression inside of the loop and then exit depending on the result. So, in effect, we're ignoring the basic functionality provided for us by the loop. Let's rewrite our loop to make it better (and shorter in code length) by incorporating the condition into the loop itself:
Dim input As String = ""
While input.ToLower() <> "quit"
input = Console.ReadLine()
Console.WriteLine(input)
End While
As you can see, we've replaced True with a more complex expression. In fact, this expression is the opposite of the expression we previously used in our If statement. Instead of checking to see if the user has typed “quit,” we check to see if the user has not typed quit. If the user hasn't, then we run the loop. The combination of less-than and greater-than symbols (<>) in the expression is actually the “not equal to” operator. Although it wouldn't be as elegant (and, indeed, I'm just pointing it out here to introduce a new operator without going too much off course), we could have instead added the Not operator to negate the earlier expression:
While Not input.ToLower() = "quit"
Also, be sure to note that we assign a value to input before we run the loop. This is because we can't run the next line's comparison using an unassigned variable. The code will compile, but the compiler will generate a warning, and an exception will be thrown at runtime.
Next: Do...Loop >>
More Visual Basic.NET Articles
More By Peyton McCullough