006.流程控制语句 Flow Control Statement

第六讲

  1. 条件运算符(三元表达式),其形式为:

    type d = a ? b : c;/*具体形式为:int d = 2 < 1 ? 3 : 4*/

    public static void main (String[] args){
        int a = 1;
        int b = 2;
        int c = 3;
        int d = 4;
        int e = a < b ? c : d;
        System.out.println(e);
    }
}
/*结果是:3*/
  1. 流程控制语句 if 的用法为:

if(布尔表达式){
    //待执行的代码
}
    public static void main (String[] args){
         int a = 1;
         int b = 2;
​
        if (a < b){
             System.out.println("executed!");
        }
    }
}
/*结果是:executed!*/
public class test{
    public ststic void main (String[] args){
        if(布尔表达式){
             //待执行的代码
        }
        else{
            // 待执行的代码
        }
    }
}
    public static void main (String[] args){
        int a = 1;
        int b = 2;
        
        if(a > b ){
            System.out.println("a>b");
        }
        else{
            System.out.println("a<b");
        }
    }
}
public class test{
    public ststic void main (String[] args){
        if(布尔表达式){
             //待执行的代码
        }
        else if(布尔表达式){
             //待执行的代码
        }
        else{
            // 待执行的代码
        }
    }
}
    public static void main (String[] args){
        int a = 1;
        int b = 2;
        
        if(a > b ){
            System.out.println("a>b");
        }
        else if(a == b ){
            System.out.println("a=b");
        }
        else{
            System.out.println("a<b");
        }
    }
}

3.switch语句,使用形式为:

    public static void main (String[] args){
        switch(变量)/*此处的变量类型就目前所学内容来看,只能为4种类型:byte,short,int,char*/{
        case 常量1:
             //待执行的代码
            break;
        case 常量2:
             //待执行的代码
            break;
        case 常量3:
             //待执行的代码
            break;
        case 常量4:
             //待执行的代码
            break;
        default:
            //待执行的代码
        }
    }
}
public class test{
    public ststic void main (String[] args){
        int a = 3;
        switch(a){
             case 1:
                    System.out.println("a == 1");
                    break;
             case 2:
                    System.out.println("a == 2");
                    break;
             case 3:
                    System.out.println("a == 3");
                    break;
             default:
                    System.out.println("default");

        }
    }
}

虽然case语句中的break是可选的,但绝大多数情况下,如果没有break,程序的逻辑就会发生错误,因此,通常情况下都需要加上break。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值