Review of branch statement java 9018

Review of branch statement java 9018

Single branch

public class condition {
    
    
    public static void main(String[] args) {
    
    
        // 分支流程应用情况就是需要做出决择的时候
        if(条件){
    
    
            条件成立时的情况;
        }

        // 例子
        if(用户年龄大于18岁){
    
    
            允许上网;
        }
    }
}

Two-way branch

public class condition {
    
    
    public static void main(String[] args) {
    
    
        // 分支流程应用情况就是需要做出决择的时候
        if(条件){
    
    
            条件成立时的情况;
        }else{
    
    
            条件不成立时的情况;
        }

        // 例子
        if(用户年龄大于18岁){
    
    
            允许上网;
        }else{
    
    
            网管让你回去写作业;
        }
    }
}

Multiple branch

public class condition {
    
    
    public static void main(String[] args) {
    
    
        // 分支流程应用情况就是需要做出决择的时候
        if(今天星期一){
    
    
            套餐一活动;
        }else if(今天星期二){
    
    
            套餐二活动;
        }else if(今天星期三){
    
    
            套餐三活动;
        }else {
    
    
            其它情况的处理;
        }
    }
}

switch branch statement

public class condition {
    
    
    public static void main(String[] args) {
    
    
        // 格式
        switch (变量) {
    
    
            case 数据1:
                变量 = 数据1的情况要执行的内容;
                break;
            case 数据n:
                变量 = 数据n的情况要执行的内容;
                break;
            default:
                变量不等于任何一个数据时会执行的语句;
                break;
        }

        // 例子
        System.out.println("请输入今天星期几:");
        String today = ipt.next();
        switch (today) {
    
    
            case "星期一":
                套餐一活动;
                break;
            case "星期二":
                套餐二活动;
                break;
            default:
                上述条件都不匹配时要执行的套餐;
                break;
        }

    }
}

The difference between switch and if

  • The condition of the if statement can be judged based on a specific value, such as today == "Monday", or based on a range, such as age<18
  • Switch branch, can only judge the situation where the data is exactly equal to a value, such as case "Monday"

Guess you like

Origin blog.csdn.net/ifubing/article/details/108664813