程序中最经典的三种执行顺序:
- 顺序结构:自上而下地执行代码
- 分支结构:根据条件,选择对应代码执行,if、switch
- 循环结构:控制某段代码重复执行,for、while、do-while
分支结构
if
if分支
- 根据条件(真或假)来决定执行某段代码
if分支的三种形式
-形式1
if(a==1){
System.out.println("if分支1");
}
- 形式2
if (a==1){
System.out.println("if分支2");
}else {
System.out.println("if分支2的else");
}
- 形式3
if (a==1){
System.out.println("if分支3的if");
} else if (a==2) {
System.out.println("if分支3的else-if");
}else {
System.out.println("if分支3的else");
}
-完整代码
package com.badidu.ifchoice;
import java.util.Scanner;
public class ifchoice {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int a = sc.nextInt();
// 1
if(a==1){
System.out.println("if分支1");
}
// 2
a = sc.nextInt();
if (a==1){
System.out.println("if分支2");
}else {
System.out.println("if分支2的else");
}
// 3
a = sc.nextInt();
if (a==1){
System.out.println("if分支3的if");
} else if (a==2) {
System.out.println("if分支3的else-if");
}else {
System.out.println("if分支3的else");
}
}
}
if使用的几个常见问题
- if(条件){},()后不能跟";"否则{}中的代码将不受if的控制
- 如果if语句的{}中只有一行代码的情况,{}可以省略不写(但是不推荐省略)
switch
switch分支
- 是通过比较值来决定执行哪条分支
switch分支的执行流程
- 先执行表达式的值,再拿着这个值区与case后的值进行匹配
- 与哪个case后的值匹配为true就执行那个case的代码块,遇到break就跳出switch分支
- 如果全部case后的值与之匹配的都是false,则执行default块的代码
switch分支的导学案例
package com.badidu.switchc;
public class switchc {
public static void main(String[] args) {
char a = 'h';
switch (a) {
case 'a':
System.out.println("age");
break;
case 'b':
System.out.println("book");
break;
default:
System.out.println("hello world!");
}
}
}
if、switch的比较,以及各自适合什么业务场景?
- if在功能上远远大于switch
- 当前条件是区间的时候,应该使用if分支结构
- 当前条件是与一个一个的值比较的时候,switch分支更适合:格式良好,性能较好,代码美观
switch使用时的注意事项
使用switch分支的几点注意事项
- 表达式类型只能是byte、short、int、char,JDK5开始支持枚举,JDK7开始支持String、不支持double、float、long
- case给出的值不允许重复,且只能是字面量,不能是变量
- 正常使用switch的时候,不要忘记写break,否则会出现穿透现象
switch穿透性在一些情况下可以简化代码
- 当存在多个case分支的代码相同时,可以把相同的代码放到一个case块中,其他的case块都通过穿透性穿透到该case块执行代码即可,这样实现简化代码
- 完整代码
package com.badidu.switchc;
public class chuantou {
public static void main(String[] args) {
char a = 'a';
switch (a) {
case 'a':
case 'b':
case 'c':
System.out.println("被穿透");
break;
case 'h':
System.out.println("is me!");
break;
default:
System.out.println("hello world!");
}
}
}