官术网_书友最值得收藏!

Using else if to make complex decisions

So far, we have learned how to decide what code we want to execute if certain conditions are met. Using if and else, we can decide what code is executed out of two parts. You are probably wondering, "What if I have many more complex decisions to make and need to be able to choose between more than two code blocks?" Yes, good question!

The else if expression is an expression that you can add after the code block belonging to the first if statement. Don't worry, it's not complicated. Let's take another example. Imagine you are driving a car and you need to check the speed limit and decide what speed you want to drive at:

Let's analyze the code:

  • Line 9: This line declares the speedLimit number variable and assigns a value of 60.
  • Line 11: The if statement checks whether the speedLimit variable is exactly 70. As we have assigned speedLimit as 60, the statement in line 11 is false, so line 12 won't be executed.
  • Line 14: The compiler will check this statement whenever the statement directly before else is false. Don't panic, it sounds very confusing now. All you need to know at the moment is that the else if statement is checked only if the previous statement isn't true.
  • Line 17: Analogically, line 17 is checked only if line 14 is false.

Of course, you can nest if statements inside each other. The syntax would look exactly the same. Simply write your new child if statement between the curly brackets of the parent statement.

主站蜘蛛池模板: 塔城市| 怀仁县| 宜兰市| 昔阳县| 弥勒县| 富平县| 贵州省| 镇赉县| 乡城县| 宿州市| 阿拉善盟| 高碑店市| 资中县| 滨海县| 探索| 梓潼县| 宿迁市| 钟山县| 白城市| 若尔盖县| 巴马| 新巴尔虎右旗| 乐东| 雷波县| 汶川县| 稻城县| 宣汉县| 加查县| 平乡县| 乌拉特前旗| 高要市| 中方县| 攀枝花市| 麟游县| 琼海市| 色达县| 铜鼓县| 平定县| 栖霞市| 镇江市| 保德县|