Thursday 6 November 2014

Java Basics Tutorial 3: Switch Statement



The switch statement

 The switch statement is a wonderful way to reduce code and make code simpler to read and follow.  Let us begin by explaining when a Switch statement would be useful. For example if you had a set of numbers which you needed different results for each. Lets say numbers 1 through 5. Okay there are a couple of ways. An IF statement would do the trick.  Ahhh but a SWITCH statement would do the same with less code and be more readable in the future if extending was required to maybe 1 through 10.

This is how they work.

SWITCH (The condition your testing)
{
   CASE 1: condition 1 is met
   break

   CASE 2: condition 2 is met
   break;

   etc etc....
 
   DEFAULT (a default is set that if no condition is met a result can still be set.)

}


Okay so how does this look in real code? For this example I will do a switch statement on a fictitious game. an imaginary dice throw which certain numbers will let your character move.


switch (dice_roll)
{
   case 1:
   character = "Move left";
   break;

   case 2:
   character = "Move right";
   break;

   case 3:
   character = "Move forward";
   break;

   case 4:
   character = "Move backwards;

   case 5:
   character = "Move down";
   break;

   case 6:
   character = "Move up";
   break;

   default = "Stay still";  

}


Well thats all there is to it. Looks clean and simple doesn't it.  Really handy thing to know and will serve you well in the future. Just remember a switch statement needs to test a condition. Each case returns a result and you should always have a default just in case no condition is met. Simple!




No comments:

Post a Comment