【Java流程控制学习】选择结构

选择结构

if单选择结构

equals:判断字符串是否相等,比较字符串的

//equals:判断字符串是否相等
if (s.equals("Hello")) {
    
    
    System.out.println(s);
}
System.out.println("End");
scanner.close();

if双选择结构

if( ) {
} else {
}

if (score >= 60) {
    
    
    System.out.println("成绩及格");
} else {
    
    
    System.out.println("成绩不及格");
}
scanner.close();

if多选择结构

if() {
} else if {
} else if {
} else {
}

if(score==100){
    
    
    System.out.println("Congratulations,full score!");
}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) {
    
    
    System.out.println("不及格");
}else {
    
    
    System.out.println("input error!");
}
scanner.close();

/* if语句至多有1个else语句,else 语句在所有的else if语句之后。

if语句可以有若干个else if语句。他们必须在else语句之前。

一旦其中一个else if 语句检测为true,其他的else if 以及else 语句都将跳过执行。

*/

嵌套的if结构

  if(score<100){
    
    
        if(score<90){
    
    
            if (score<80){
    
    
                if (score<70){
    
    
                    if (score<60){
    
    
                        System.out.println("不及格");
                    }else{
    
    
                        System.out.println("D级");
                    }
                }else{
    
    
                    System.out.println("C级");
                }
            }else{
    
    
                System.out.println("B级");
            }
        }else{
    
    
            System.out.println("A级");

        }

    }else if(score==100){
    
    
        System.out.println("Congratulations,full score!");
    }else{
    
    
        System.out.println("input error!");
    }
    scanner.close();
}

switch多选择结构

switch case 语句判断一个变量与一系列值中某个值是否相等,每个值称为一个分支。

变量可以是:

  • byte、short、int或者char。

  • 从javaSE 7开始,switch 支持字符串String 类型了

  • 同时case 标签必须为字符串常量或字面量。

    switch (expression) {

    ​ case value :

    ​ //语句

    ​ break;//可选

    ​ case value:

    ​ //语句

    ​ break;//可选

    //你可以有任意数量的case语句

    default://可选

    ​ //语句

    }

//case穿透现象,末尾如果不加break;会从该语句一直执行完
//switch匹配一个具体的值

String code = "200";

switch (code){
    
    
    case"200":
    case"201":
    case"202":
        System.out.println("成功");
        break;
    case"401":
        System.out.println("资源未发现");
        break;
    case "500":
        System.out.println("未知错误");
        break;
    default:
        System.out.println("未知错误");
        break;
        //200,201,202都会输出"成功",利用穿透特性
} 
注意点:

1.一般每个 case 后面都会加上break;

2.case后面只能接常量;

3.default 后面也要接break;避免后面再添加语句;

猜你喜欢

转载自blog.csdn.net/weixin_44302662/article/details/114156147