switch

本文深入探讨了Java中switch语句的使用方法,包括基本语法、case与default的执行流程,以及字符、数字、枚举和字符串作为条件的示例。通过具体代码演示了不同输入下的执行结果。
class Test{
    public static void main(String[] args) {
       int i = 9;
       switch (i){
           default:
               System.out.println("default");
           case 0:
               System.out.println("zero");
           case 1:
               System.out.println("one");
           case 2:
               System.out.println("two");
       }
    }
    }

default
zero
one
two

switch语句将表达式的值与每个case中的目标值进行匹配,如果找到了匹配的值,就会执行对应case后的语句;如果没有找到任何匹配的值,就会执行default后的语句,如果switch语句中没有default,则case语句统统不执行。default让我想起了异常与捕获中finally语句的作用,不管default放在switch语句的什么位置,程序在运行的过程中,default后面的语句统统都会执行,除非遇到break。
switch(数字|枚举|字符|字符串){
case 内容1:{
内容满足时执行语句;
[break;]
}
case 内容2:{
内容满足时执行语句;
[break;]
}
……
default:{
内容都不满足时执行语句;
[break;]
}
}

public class Test{
    public static void main(String[] args) throws IOException {
        System.out.println("请输入字符:");
        char c = (char)System.in.read();
        switch (c){
            case 'a':{
                System.out.println("lt takes lots of tactical moves in order to win a game of chess");
            }
            case 'b':
                System.out.println("They sent an assassin to kill me");
                default:
                    System.out.println("My meditation practice relaxes me and calms my mind");
        }
    }
}

当输入a时,执行结果为:
lt takes lots of tactical moves in order to win a game of chess
They sent an assassin to kill me
My meditation practice relaxes me and calms my mind
当输入d时,执行结果为:
My meditation practice relaxes me and calms my mind

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值