java基础5_if、switch控制语句

一、判断语句

1.if 的第一种格式

if(关系表达式){
语句体;
}
当关系表达式结果为true,执行语句体
如果为false,不执行语句体

package test;

public class DemoIF {
    public static void main(String[] args) {
        int a = 10;
        if(a % 2 == 0){
            System.out.println("a 是偶数");
        }
        System.out.println("if 测试");
    }
}

2.if–else语句

if (关系表达式){
语句体1;
}else{
语句体2;
}
如果关系表达式为true,输出语句体1;
如果关系表达式为false,输出语句体2;

package test;

public class DemoIfElse {
    public static void main(String[] args) {
        int a = 10;
        if(a % 2 == 0){
            System.out.println("a 是偶数");
        }else {
            System.out.println("a是奇数");
        }
        System.out.println("if--Else 测试");
    }
}

if …else if…else

if (判断语句1){
执行语句1;
}else if (判断语句2){
执行语句2;
}else{
执行语句n;
}

如果判断语句1 为true,运行执行语句1,然后结束;
如果判断语句1为false,执行判断语句2;如果判断语句2为true,运行执行语句2,然后结束;否则运行执行语句n;

package test;

public class DemoIfElseExt {
    public static void main(String[] args) {
        int x = 10;
        int y;
        if (x >= 3){
            y = 2*x +1;
        }else if(-1 < x && x <3){
            y = 2 *x;
        }else {
            y = 2*3 -1;
        }
        System.out.println(y);
    }
}

二、选择语句

2.1 switch语句

switch (表达式){
case 常量值1:
语句体1;
break;
case 常量值2:
语句体2;
break;
default:
语句体n;
break;
}
首先计算出表达式的值;
然后和case依次比较,一旦有对应的值,则执行对应的语句体,然后结束;
最后如果所有case和表达式的值都不匹配,则执行default;

public class DemoSwitch {
    public static void main(String[] args) {
        int num = 4;
        switch (num){
            case 1:
                System.out.println("星期一");
                break;
            case 2:
                System.out.println("星期二");
                break;
            case 3:
                System.out.println("星期三");
                break;
            case 4:
                System.out.println("星期四");
                break;
            case 5:
                System.out.println("星期5");
                break;
            default:
                System.out.println("输入错误");
                break;
        }
    }
}

2.2case穿透性

在switch语句中,如果case后面不写break,将出现穿透现象,也就是不会判断下一个case的值,直接向后运行,直到遇到break,或者整体switch结束。
输出:星期四、星期五、输入错误
···
public class DemoSwitch {
public static void main(String[] args) {
int num = 4;
switch (num){
case 1:
System.out.println(“星期一”);
break;
case 2:
System.out.println(“星期二”);
break;
case 3:
System.out.println(“星期三”);
break;
case 4:
System.out.println(“星期四”);
case 5:
System.out.println(“星期5”);
default:
System.out.println(“输入错误”);
break;
}
}
}
···

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值