控制语句switch

2018-11-01  本文已影响3人  张轻舟

语法

switch(表达式){

case 值1:
    java语句;
    break;

case 值2:
    java语句;
    break;

case 值3:
    java语句;
    break;

default:
    java语句;
}

例:

    int week = 1;

    switch(week) {
        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("今天是星期五");
            break;
        case 6:
            System.out.println("今天是星期六");
            break;
        case 7:
            System.out.println("今天是星期日");
            break;
        default:
            System.out.println("数字错误");
    }

执行流程

例:

String actor = "吴京";

    switch(actor) {
        case "成龙":
            System.out.println("代表作《警察故事》");
        case "李连杰":
            System.out.println("代表作《黄飞鸿》");
        case "吴京":
            System.out.println("代表作《战狼》");
        default:
            System.out.println("我是一个演员");

    }
打印季节:

int month = 3;
switch (month) {
    case 3:
    case 4:
    case 5:
        System.out.println(month + "月是春季");
    break;
    case 6:
    case 7:
    case 8:
        System.out.println(month + "月是夏季");
    break;
    case 9:
    case 10:
    case 11:
        System.out.println(month + "月是秋季");
    break;
    case 12:
    case 1:
    case 2:
        System.out.println(month + "月是冬季");
    break;
    default:
        System.out.println("对不起没有对应的季节");
    break;
}
上一篇 下一篇

猜你喜欢

热点阅读