Learning VB.NET: Working with Variables, Conditionals, and Console Input
This is the third article in a series covering how to learn VB.NET by developing a text-based game. The last article covered working with the console and how to change color schemes. This one will discuss defining variables, conditionals, and Console input. So if you're ready to keep learning, then keep reading!
We need to cover a few more things before we can begin work on the game itself. The first is very important, and I'm afraid that perhaps I've already put it off too long. In order to make any sort of useful program, we need to be able to work with variables. Languages differ greatly in how they treat variables, and Visual Basic is no exception here. So, let's get started.
Let's say that we want an Integer object called number. There are two things that are important here: the name of the variable (number) and the type of the variable (Integer). We need to explicitly define both when we create a new variable because Visual Basic is both strongly- and statically-typed. Here's how it's done:
Dim number AsInteger
The above declaration is fairly straightforward, as it should be. The thing to note here is the Dim keyword. The Dim keyword is designed to declare and allocate space for a variable. Also, note how the variable name goes before the type name, which is different from many other languages. The variable name and the type name are separated by As (after all, we're declaring number as an Integer).
Now that we've declared a variable, we need to assign something to it. Naturally, we'll have to assign an Integer to our variable. Assignment is done with the assignment operator and resembles assignment in other languages:
number = 3
Above, there are no surprises. We put the variable, the assignment operator, and then the value to be assigned to the variable.
We can also define a variable and assign it a value in the same step. Let's combine these processes using the above example:
Dim number AsInteger= 3
As you can see, we simply combine the declaration step with part of the assignment step. This looks neat with the example we've chosen because we're only working with an Integer, and we're not instantiating a new object. However, let's consider a more complex object that we must explicitly instantiate. Let's create another variable containing a Date object:
Dim anotherVariable AsDate= NewDate()
Aside from declaring and assigning to a variable, the above line of code does something else very important: it instantiates a Date object. The Date type is used to represent a date and time. Instantiation in Visual Basic is not wildly different from instantiation in other languages, as you can see above. We simply use the New keyword and call the appropriate constructor.
Back to declaration and assignment, though. The above code does look a bit redundant. The type is essentially specified twice, and very close together, too. It looks a bit ugly, but, thankfully, there's another way to do this. In fact, the above method is discouraged, and I only brought it up so that you may recognize it if you ever encounter it. The other method is more concise:
Dim anotherVariable AsNewDate()
This looks much neater and more elegant, and it's the style you should always use if you need to declare a variable and assign a newly instantiated object to it in one step.
So far, we've used the console for output, but our game, of course, needs to be able to accept input from the user. Now that we know how to work with variables, we can start tackling input. As with output, the Console class is used for input. With output, we started with the WriteLine procedure, and with input, we'll start with ReadLine. Whereas WriteLine writes a complete line to the console, ReadLine reads a complete line from the console (that is, the user). The input is then stored in a string. Here's ReadLine in action:
Dim input AsString= Console.ReadLine()
Console.WriteLine(input)
The first line of the above snippet reads a line of input from the user, and the second line writes the line back out to the user.
ReadLine will work fine for many purposes. For example, we might ask the user his name, which he'll type in and then press enter. However, ReadLine is not appropriate for input because not all input will be in line format. For example, when the user wants to move around, he'll press an arrow key. We'll then need to intercept the pressed key and treat it as an individual key rather than a line. For situations like this, we'll need to use the ReadKey function, which reads an individual key from the console and then returns information about the key in the form of a ConsoleKeyInfo object. Here's a basic example of ReadKey:
Dim input AsConsoleKeyInfo = Console.ReadKey()
Our ConsoleKeyInfo object has a number of properties that describe the key pressed. One property is the KeyChar property, which will return the character representation of the key pressed:
Console.WriteLine("You pressed the '{0}' key.", input.KeyChar)
However, this property has some limitations. ReadKey will not only read basic alphanumeric keys, but it will also read other keys, such as function keys, that do not have appropriate character representations. For example, try running the above two lines of code and then pressing the F1 key.
The next property of a ConsoleKeyInfo object is Key. The Key property will return a value from the ConsoleKey enumeration. This enumeration contains values for all of the keys. So, to check which key has been pressed, one would simply need to compare the value in Key with the values in the ConsoleKey enumeration. To do this, however, we need to take a look at conditionals.
There are two types of conditionals in Visual Basic. The first type of conditional is the If ...Then ...Else statement, and the second type of conditional is the Select ...Case statement. Let's take a look at the If ...Then ...Else statement first. We'll create a short code snippet that accepts keyboard input and then checks to see if the user has pressed the F1 key. If the user has, then a message is displayed.
Dim input AsConsoleKeyInfo = Console.ReadKey()
If input.Key = ConsoleKey.F1 Then
Console.WriteLine("You pressed F1.")
EndIf
We check to see if the Key property of our ConsoleKeyInfo object is equal to the F1 value of the ConsoleKey enumeration. One thing worth mentioning is the equivalence operator in Visual Basic. Instead of using two equals signs, as in other languages, only one is used. Anyway, back to the code. If the user presses the F1 key, then a message is displayed. Otherwise, nothing is done.
Let's say, though, that in addition to displaying a message when the F1 key is pressed, we want to display a message if another key is pressed instead. To do this, we need to add an Else block:
Dim input AsConsoleKeyInfo = Console.ReadKey()
If input.Key = ConsoleKey.F1 Then
Console.WriteLine("You pressed F1.")
Else
Console.WriteLine("You pressed another key besides F1.")
EndIf
Now let's say that we want to display a special message for F2 in addition to a special message for F1. To do this, we need to add an ElseIf block, which is similar in structure to If:
Dim input AsConsoleKeyInfo = Console.ReadKey()
If input.Key = ConsoleKey.F1 Then
Console.WriteLine("You pressed F1.")
ElseIf input.Key = ConsoleKey.F2 Then
Console.WriteLine("You pressed F2.")
Else
Console.WriteLine("You pressed another key besides F1 or F2.")
EndIf
If ...Then ...Else works for complex situations, such as when the expressions are very different, or for situations where not many expressions need to be tested. Let's say, however, that we need to check for multiple keys. We could keep adding ElseIf statements, and our program would work fine. However, things would get messy and redundant. A better method would be to use a Select ...Case statement, which compares one value to numerous other values. So, with our example, we'd be comparing the Key property to values in the ConsoleKey enumeration. Let's convert the above code to a Select ...Case statement.
Dim input AsConsoleKeyInfo = Console.ReadKey()
SelectCaseinput.Key
Case ConsoleKey.F1
Console.WriteLine("You pressed F1.")
Case ConsoleKey.F2
Console.WriteLine("You pressed F2.")
CaseElse
Console.WriteLine("You pressed another key besides F1 or F2.")
EndSelect
In the first line of our Select ...Case, we specify our test expression. We then match the result of this expression with other values. Here, we match Key with possible values in the ConsoleKey enumeration. The result, in any case, is the same as before, except the code is a bit neater, and it would be neater still in comparison if we were to test for more keys. Needless to say, we'll be using Select ...Case when dealing with key presses in our game.
You may have noticed, if you've been running the examples, that the pressed keys are displayed on the screen. Sometimes, this is not appropriate, but, thankfully, we can prevent this from happening. ReadKey takes an optional Boolean specifying whether or not to hide input:
' Hide the pressed key
Dim input AsConsoleKeyInfo = Console.ReadKey(True)
' Show the pressed key
input = Console.ReadKey(False)
The above lines also show something that I've neglected to mention so far: comments. Comments can be made using the apostrophe/single quotation mark key. While they can follow a line of code, it's good practice putting comments on lines by themselves.
That's it for now. Be sure to join us in the next installment of the series.