Discovering Visual Basic .NET: Making Decisions
In the previous article in this series, you discovered functions arguments and and how they work. In this article, I'll show you how to make your programs smarter by letting them make their own decisions.
Your programs can make decisions on their own based on information they gather. But first, you have to tell your programs which decisions to make and how to make them. The keywords you use to do that, naturally enough, are If and Then:
If condition Then statementEnd If
This If...Then structure is often called a conditional. A conditional has two parts:
- The condition, or the question part
- The statement, or the thing-to-do part
The End If just tells you when the statement part is over.
Here's an example. The computer spins a wheel that has five sections numbered 1 through 5, and I bet on number 3 coming up:
Imports SystemImports Microsoft.VisualBasicModule SpinTheWheel Public Sub Main() Dim Wheel, Won As Integer Randomize Console.WriteLine("I'm looking for a 3") Console.WriteLine("and spinning the wheel!") Wheel = Int(Rnd * 5) + 1 ' Random number: 1-5 Console.WriteLine("The Wheel landed on " & Wheel) If Wheel = 3 Then Won = 50 Console.WriteLine("It landed on my number!") Console.WriteLine("I win $" & Won) End If Console.WriteLine("All done.") End SubEnd Module
First, I display a little text to explain the premise of the game. I spin the wheel by generating a random number between 1 and 5. Then, I display the value that the wheel landed on. (For more information on Randomize, Rnd, and this formula used to generate random numbers, see the previous article in this series.)
Next up is the If...Then statement. The condition part of the If...Then asks the question, "Does the Wheel variable hold a value that equals 3?" Everything between the Then and the End If is the statement portion. If the condition is true, the statement portion is performed. If the condition is not true, the statement portion is ignored. So, in this case, if Wheel equals 3, two things happen:
- The Won variable is set to 50.
- The program displays this:
It landed on my number!I win $50
Now, if you haven't already, try out this example. Run it several times so that you can see what it does both in a win and a lose scenario.
Note: If you keep running the program, you'll notice that the Won variable doesn't accumulate an additional $50 every time you win. That's because the variable is reset every time you run the program.