java有两钟选择判断语句,分别是if else和switch case语句。

  下面我们做一个switch case语句的练习。

        // 定义一个扫描器
        Scanner sacnner = new Scanner(System.in);
        // 定义一个变量用于接收用户输入的月份
        int month=sacnner.nextInt();
        
        switch (month) {
        case 1:
            System.out.println(month + "月份是冬天");
            break;
        case 2:
            System.out.println(month + "月份是冬天");
            break;
        case 3:
            System.out.println(month + "月份是春天");
            break;
        case 4:
            System.out.println(month + "月份是春天");
            break;
        case 5:
            System.out.println(month + "月份是春天");
            break;
        case 6:
            System.out.println(month + "月份是夏天");
            break;
        case 7:
            System.out.println(month + "月份是夏天");
            break;
        case 8:
            System.out.println(month + "月份是夏天");
            break;
        case 9:
            System.out.println(month + "月份是秋天");
            break;
        case 10:
            System.out.println(month + "月份是秋天");
            break;
        case 11:
            System.out.println(month + "月份是秋天");
            break;
        case 12:
            System.out.println(month + "月份是冬天");
            break;
        default:
            System.out.println("不合法的输入");

        }

但是在编程时我们要尽量简化代码,让代码更简洁,便于观看,在这里我们可以利用switch语句的语法合并同一季节的输出语句

        // 定义一个扫描器
        Scanner sacnner = new Scanner(System.in);
        // 定义一个变量用于接收用户输入的月份
        int month=sacnner.nextInt();
        
        switch (month) {
        case 12:
        case 1:
        case 2:
            System.out.println(month + "月份是冬天");break;
        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;
        default:
            System.out.println("不合法的输入");

        }

 

posted on 2017-03-09 19:23  人生第一步  阅读(1895)  评论(0编辑  收藏  举报