【java基础】分支结构if-else、switch-case

1.if-else

int a = 10;
if(a==0){
	System.out.println("a等于0");
}else if(a<0){
	System.out.println("a小于0");
}else{
	System.out.println("a大于0");
}

(1)条件表达式必须是布尔表达式(结果为true或false)
(2)if-else可以嵌套使用
(3)多个条件表达式之间没有交集,顺序无所谓;多个条件表达式是包含关系时,范围小的声明在上,否则范围小的就没机会执行了。

2.switch-case

        int i = 0;
        switch (i) {
            case 0:
                System.out.println("Zero");
                break;
            case 1:
                System.out.println("One");
                break;
            default:
                System.out.println("Default");
                break;
        }

规则
(1)switch(表达式)中表达式的值必须是下述集中类型之一:
byte、short、char、int、枚举(jdk5.0)、String(jdk7.0)
(2)case子句中的值必须是常量,不能是变量名或不确定的表达式值。
(3)同一个switch,所有case子句中的常量值互不相同。
(4)break语句用来跳出switch语句块;如果没有break,程序会顺序执行到switch结尾。
(5)default是可选的,位置也是灵活的(可以写在两个case中间,一般写在最后)。当没有匹配的case时,执行default。

posted @ 2022-08-19 10:46  植树chen  阅读(55)  评论(0编辑  收藏  举报