一、if分支
语法格式:
if (条件) {
语句体
}
条件必须是布尔类型的数据(true或者false)
执行流程:
如果条件为true的话,就执行条件后面大括号里面的语句体。如果条件为false,就跳过大括号里面的内容去执行下面的代码。
public class Demo2 {
public static void main(String[] args) {
int money = 9;
if (money > 10) {
System.out.println("可以买兰博基尼了");
}
System.out.println("程序结束");
}
}
二、if-else分支
语法格式:
if (条件) {
语句体1
} else {
语句体2
}
执行流程:
当成程序运行到if-else之后,首先判断条件,如果条件为true的执行语句体1。如果条件为false执行语句体2,两者只能选择其一。
public class Demo3 {
public static void main(String[] args) {
int a = 19;
if (a >= 10) {
System.out.println("今天中午吃顿好的!");
} else {
System.out.println("西北风");
}
System.out.println("程序结束");
}
}
三、if-else if分支
语法格式:
if (条件1) {
语句体1
}else if(条件2) {
语句体2
} else if (条件3) {
语句体3
} else if(条件4) {
语句体4
} else {
语句体5
}
执行流程:
当程序运行到if的时候,首先判断小括号里面条件1,如果条件1为false就跳过语句体1,执行下面的else if 的条件2,直到条件为true,就执行语句体,下面的条件就不用再判断了。
public class Demo4 {
public static void main(String[] args) {
int score = 70;//先定义一个变量 值为70
if (score >= 90 && score <= 100) {
System.out.println("优秀");
} else if (score >= 80) {
System.out.println("良好");
} else if (score >= 70) {
System.out.println("一般");
} else if (score >= 60) {
System.out.println("及格");
} else {
System.out.println("叫家长");
}
}
}
四、switch-case分支
switch(表达式) {
case 常量1:
语句体1;
break;
case 常量2:
语句体2;
break;
case 常量3:
语句体3;
break;
default:
语句体n;
break;
}
public class Demo1 {
public static void main(String[] args) {
System.out.println("请输入一个月份:");
Scanner scanner = new Scanner(System.in);//从控制台获取数据
int month = scanner.nextInt();//获取int类型的数据
if (month <= 0 || month > 12) {
System.out.println("输入月份有误,请请重新输入!!!");
System.exit(0);//程序结束
}
if (month >= 3 && month <= 5) {
System.out.println("春季");
}else if (month >= 6 && month <= 8) {
System.out.println("夏季");
}else if (month >= 9 && month <= 11) {
System.out.println("秋季");
}else{
System.out.println("冬季");
}
}
}