Sometimes you need to evaluate the value of a sensor or some other data and depending on the value to execute one action or other. In a way we have achieved that so far, using the switch block, but we have had only two cases - if the statement is true do one thing and if the statement is false do another. However, sometimes we need more than two cases and then we use the switch block as a switch statement.
- 26 Sep 2018
The switch block can be used as a switch statement with Brick Buttons, Colour Sensor, Infrared Sensor, Text and Numeric. For the purpose of this tutorial, we will explore only the switch block using the Numeric mode. First of all, put a switch block and set it to numeric:
As you can see there are two cases - one if the value is 0 and one if the value is 1. If we want to add more cases, we can do it by selecting the plus sign shown bellow:
Afterwards we set the desired value:
The same way using the "x" sign, next to the value for each case
we can remove the corresponding case:
So the switch block evaluates the numeric value and if the value of a given case is the same, it will execute the blocks within the case. However, it may happen that the value passed to the switch block does not match any of the cases. Then the default case is executed. The default case is one of all given cases and is marked with a dot:
You can change the default case by just selecting any other case as shown:
Note that if you delete the defaut case, the first case will become default:
A good practice is to have a case with a value, that can not be met, usually -1. That case is set to default and covers any errors and unexpected data. Withing the case you can put a sound block with "Error" or some other notification for the occured error.
Everything above is true, when the switch is in tabbed view. You can add a new case from the plus sign:
delete from the 'x' next to each case
and set the default case:
Courses and lessons with this Tutorial
This Tutorial is used in the following courses and lessons