day12 switch多选择结构及while循环

switch多选择结构

  • 多选择结构还有一个实现方式就是switch case语句。

  • switch case语句判断一个变量与一系列值中某个值是否相等,每个值称为一个分支。

  • 看源码

  • switch语句中的变量类型可以是:

    • byte、short、int或者char。
    • 从Java SE7开始
    • switch支持字符串string类型了
    • 同时case标签必须为字符串常量或字面量。
switch(expression){
    case value:
        //语句
        break;//可选
    case value:
        //语句
        break;//可选
        //你可以有人以数量的case语句
    default://可选
        //语句
}

例:

package com.wangchuan.struct;

public class switchDemo01 {
    public static void main(String[] args) {
        //case穿透    //switch 匹配一个具体的值
        char grade = 'B';

        switch(grade){
            case  'A':
                System.out.println("优秀!");
                break;//可选
            case 'B':
                System.out.println("良好");
                //break;
            case 'C':
                System.out.println("及格");
                break;
            case 'D':
                System.out.println("继续努力");
            case 'E':
                System.out.println("挂科");
            default:
                System.out.println("未知等级");

        }


    }
}

package com.wangchuan.struct;

public class switchDemo02 {
    public static void main(String[] args) {

        String name = "川子";
        //JDK7的新特性,表达式结果可以是字符串!!!
        //字符的本质还是数字
        //反编译  java---class(字节码文件)---反编译(IDEA)


        switch (name){
            case "川子":
                System.out.println("川子");
                break;
            case"王子":
                System.out.println("王子");
                break;
            default:
                System.out.println("你是谁?");
        }
    }
}

循环结构

  • while循环

  • do...while循环

  • for循环

  • 在Java5中引入了一种主要用于数组的增强型for循环。

while循环

  • while是最基本的循环,它的结构为:
while(布尔表达式){
    //循环内容
}
  • 只要布尔表达式为true,循环就会一直执行下去。
  • 我们大多数情况是让停止下来,我们需要一个让表达式失效的方式来结束循环。
package com.wangchuan.struct;

public class whileDemo01 {
    public static void main(String[] args) {

        //输出1-100

        int i = 1;

        while (i <= 100){
            System.out.println(i);
            i++;
        }
    }
}

  • 少部分情况需要循环一直执行,比如服务器的请求响应监听等。
package com.wangchuan.struct;

public class whileDemo02 {

    public static void main(String[] args) {
        while (true){
            //等待客户端连接
            //定时检查
            //。。。。

        }
    }
}

  • 循环条件一直为true就会造成无限循环【死循环】,我们正常的业务编程中应该尽量避免死循环。会影响程序性能或者造成程序卡死崩溃!
  • 思考:计算1+2+3+......+100=?
package com.wangchuan.struct;

public class whileDemo03 {
    public static void main(String[] args) {
        //计算1+2+3...+100
        int i = 1;
        int sum = 0;

        while (i <= 100){
            sum = sum + i;
            i++;
        }
        
        System.out.println(sum);
    }
}

posted @ 2021-03-07 21:02  圈圈子  阅读(124)  评论(0)    收藏  举报