1.if -else
Notes on if -else: If there is no intersection between the conditions, the order of the conditions can be reversed.
If there is intersection between the conditions, the order of the conditions can not be reversed.
2. switch-case
Notes on switch-case:
- the value of the expression in switch (expression) must be one of the fllowing types: byte, short, char, int, enum, String
- the value in the case clause must be a constant, not a variable name or indeterminate expression value or range.
- In the same switch statement, the constant values in all case clauses are different from each other.
- The break statement is used to make the program jump out of the switch statement block after executing a case branch; if there is no break, the program will be executed sequentially to the end of the switch.
- The default clause is optional. At the same time, the location is also flexible. When there is no matching case, the default statement is executed.
if-else statement compared to switch-case statement
if-else语句优势
- if语句的条件是一个布尔类型值,if条件表达式为 true则进入分支,可以用于范围的判断,也可以用于等值的判断,使用范围更广。
-
switch语句的条件是一个常量值(byte,short,int,char,枚举,String),
只能判断某个变量或表达式的结果是否等于某个常量值,使用场景较狭窄。
switch语句优势
- 当条件是判断某个变量或表达式是否等于某个固定的常量值时,使用 if和 switch都可以,习惯上使用 switch更多。因为效率稍高。当条件是区间范围的判断时,只能使用 if语句。
- 使用 switch可以利用穿透性,同时执行多个分支,而 if...else没有穿透性。
3.for循环
如何结束一个循环结构?
- 循环结构中的循环条件部分返回false.
- 循环结构中执行了break.
- 如果一个循环结构不能结束,那就是一个死循环!我们开发中要避免出现死循环
4. 产生随机数
随机数 Math.random()产生 [0,1)范围内的小数
如何获取[a,b]范围内的随机整数呢?(int)(Math.random() * (b - a + 1)) + a