- if 语句第三种格式: if…else if …else
if (判断条件1) {执行语句1;}else if (判断条件2) {执行语句2;}else if (判断条件n) {执行语句n;}else {执行语句n+1;}
执行流程
- 首先判断关系表达式1看其结果是 true 还是 false
- 如果是 true 就执行语句体1,然后结束当前多分支
- 如果是 false 就继续判断关系表达式2看其结果是 true 还是 false
- 如果是 true 就执行语句体2,然后结束当前多分支
- 如果是 false 就继续判断关系表达式…看其结果是 true 还是 false
- …
- 如果没有任何关系表达式为 true ,就执行语句体n+1,然后结束当前多分支

语法案例演示1:
计算如下函数:x 和 y 的关系满足如下:
(1)x>=3; y = 2x + 1;
(2)-1<=x<3; y = 2x;
(3)x<-1; y = 2x – 1;
从键盘输入 x 的值,计算出 y 的值并输出
public static void main(String[] args) {java.util.Scanner input = new java.util.Scanner(System.in);System.out.print("请输入x的值:");int x = input.nextInt();int y;if (x>= 3) {y = 2 * x + 1;} else if (x >= -1 && x < 3) {y = 2 * x;} else {y = 2 * x - 1;}System.out.println("y的值是:"+y);}
public static void main(String[] args) {java.util.Scanner input = new java.util.Scanner(System.in);System.out.print("请输入x的值:");int x = input.nextInt();int y;if (x>= 3) {y = 2 * x + 1;} else if (x >= -1) {y = 2 * x;} else {y = 2 * x - 1;}System.out.println("y的值是:"+y);}


语法案例演示2:
通过指定考试成绩,判断学生等级
- 90-100 优秀
- 80-89 好
- 70-79 良
- 60-69 及格
- 60以下 不及格
public static void main(String[] args) {int score = 89;if(score<0 || score>100){System.out.println("你的成绩是错误的");}else if(score>=90 && score<=100){System.out.println("你的成绩属于优秀");}else if(score>=80 && score<90){System.out.println("你的成绩属于好");}else if(score>=70 && score<80){System.out.println("你的成绩属于良");}else if(score>=60 && score<70){System.out.println("你的成绩属于及格");}else {System.out.println("你的成绩属于不及格");}}

public static void main(String[] args) {int score = 89;if(score<0 || score>100){System.out.println("你的成绩是错误的");}else if(score>=90){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("你的成绩属于不及格");}}

