Java 流程控制:if多选择机构
-
我们发现刚才的代码不符合实际情况,真实的情况还可能存在ABCD四个选择,存在区间多级判断。比如90-100就是A,80-90就是B..等等,在生活中我们很多时候的选择也不仅仅是两个,所以我们需要一个多选择结构来处理这类问题!
-
![]()
-
语法
-
if(布尔表达式1){
//如果布尔表达式1的值为true执行代码
}else if(布尔表达式2){
//如果布尔表达式2的值为true执行代码
}else if(布尔表达式3){
//如果布尔表达式3的值为true执行代码
}else{
//如果以上布尔表达式都不为true执行代码
} -
package com.Ji.struct;
import java.util.Scanner;
public class ifDemo03 {
public static void main(String[] args) {
//成绩多级判断 考试分数大于60是及格,小于60分就不及格。
//在一个if语句至多有一个else语句并且要在最后,else语句在所有的else if语句之后
//if 语句可以有若干个else if语句,他们必须在else 语句之前。
//一旦其中一个else if 语句检测为true ,其他的else if 以及else语句都将跳过执行
Scanner scanner = new Scanner(System.in);
System.out.println("请输入成绩:");
int score = scanner.nextInt();
if (score==100){
System.out.println("恭喜满分");
}else if (score<100&&score>=90){
System.out.println("A级");
}else if (score<90&&score>=80){
System.out.println("B级");
}else if (score<80&&score>=70){
System.out.println("C级");
}else if (score<70&&score>=60){
System.out.println("D级");
}else if (score<60&&score>=0){
System.out.println("不及格");
}else {
System.out.println("成绩不合法");
}
scanner.close();
}
}
嵌套的if结构
-
使用嵌套的if...else 语句是合法的。也就是说你可以在另一个if或者else if语句中使用if 或 else if语句。你可以像if语句一样嵌套else if....else.
-
语法
-
if(布尔表达式1){
//如果布尔表达式1的值为true执行代码
if(布尔表达式2){
//如果布尔表达式2的值为true执行代码
}
} -
思考?根据比赛成绩及性别,对选手进行分组,当成绩小于等于10秒时选手有资格进入决赛,在根据性别男和女分别进入男子组决赛和女子组决赛
package com.Ji.struct;
import java.util.Scanner;
public class ifDemo06 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("请输入成绩:");
int score=scanner.nextInt();
if (score<=10){
System.out.println("请输入性别:");
String sex =scanner.next();
if ("男".equals(sex)){
System.out.println("恭喜进入男子组决赛!");
}else if ("女".equals(sex)){
System.out.println("恭喜进入女子组决赛!");
}
}else {
System.out.println("请继续努力!");
}
scanner.close();
}
}

浙公网安备 33010602011771号