Fork me on GitHub

java流程控制

java流程控制语句
1.if的三种格式

格式1:
public class TestIf {
        public static void main(String[] args) {
            //流程控制语句:if
            //格式1:一般作为单条件判断
            int age = 17;
            if (age>=18) {
                System.out.println("你已经成年了!");
            }
            System.out.println("over!");

        }
    }
格式2:

public class TestIf {
    public static void main(String[] args) {
        //流程控制语句:if
        //格式2:不是失败就是成功,只会执行其中一个,不可能两个都执行
        String username = "admin";
        String password = "admin";
        if (username == "admin" && password =="admin"){
            System.out.println("登录成功!");
        }else{
            System.out.println("登录失败!");
        }
    }
}

格式3:
public class TestIf {
    public static void main(String[] args) {
        //流程控制语句:if
        //格式3:判断条件2个以上,if ……else if ……else,只会执行一个条件,条件都是互斥的
        int score = 90;
        if (score >= 90 && score <= 100) {
            System.out.println("优");
        } else if (score >= 70 && score < 90) {
            System.out.println("良");
        } else if (score >= 60 && score < 70) {
            System.out.println("及格");
        } else if (score >= 0 && score < 60) {
            System.out.println("不及格");
        } else {
            System.out.println("输入的分数不正确");
        }
        System.out.println("end……");

    }
}    

循环

  • for循环
public class TestFor {
    public static void main(String[] args) {
        //循环
        /*
        格式:
        for(初始化语句1; 条件判断语句2; 循环体执行后的语句4){
            循环体3;
        }
         */
        //求和
        int s = 0;
        for (int i = 1; i <= 100; i++) {
            s = s + i;
        }
        System.out.println(s);

      //遍历数组
      int[] arr = {1, 22, 33, 1213, 213};
      for (int i = 0; i < arr.length; i++) {
          System.out.println(arr[i]);
      }

    // 增强for,不能直接拿到索引,只能从头拿到尾,不能倒叙遍历
    //增强for 遍历数组
      /*
      for(数据类型 变量名 : 数组或集合名){
      }
       */

      System.out.println("#################");
      for (int e: arr){
          System.out.println(e);
      }

    //continue使用
    for (int i = 1; i < 10; i++) {
          if (i % 3 == 0) {
              continue;   //continue结束本次循环,继续下次循环
          }
          System.out.println(i);
     }
      
    }
}

while循环*

    public class WhileLoop {
      public static void main(String[] args) {
        //while循环
        /**
         * 初始化语句1
         * while(条件判断语句2){
         *     循环体3;
         *     循环体执行之后的语句4;
         * }
         */
        int i = 1;
        while (i <= 5){
            System.out.println(i);
            i++;
        }
    }
  }
posted @ 2021-07-14 12:55  yanzi_anqi  阅读(24)  评论(0编辑  收藏  举报
页脚Html代码