1 2 3 4 5 6 7 8 9 10 11 12 13
Isn't it annoying how you have to specify the variable to compare and the
== comparison operator over and over again? Well this is where 'switch' statements become very useful!
Switch statements are pretty much just an easy way to compare one variable to a variety of values. You begin a switch statement by firstly using the
switch keyword, and then specifying the variable you want to evaluate in some regular brackets. You then specify the different cases (comparisons) inside curly brackets - we'll learn how to formulate these in a second. So you should be imagining something that looks a bit like this:
1 2 3 4 5 6
So let's learn how to create cases! We can specify a case inside the curly brackets by writing the keyword
case followed by the value we want to compare (to 'uInput' in this case), followed by a colon. We then put any code we want executed when this case is met, and then end the case with the 'break' keyword followed by a semicolon. For example:
1 2 3 4 5 6 7 8
So let's just go ahead and build in all the functionality that the small code snippet at the beginning of this tutorial had by simply adding some more cases to our 'switch' statement:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
On running this, we should see that everything seems exactly the same as the code at the beginning of this tutorial, but our code is a lot cleaner, easier, and generally, in my opinion, better! But how do you accomplish 'else' type statements using switch statements? Luckily, with extreme ease!
If we wanted to add an 'else' case to our switch statement, we simply have to add a case called
default (we don't even have to write the
case keyword) - this will execute if none of the other cases are met.