• java循环


    Java循环

    1、 循环三要素

    a)       循环变量值初始化

    b)      循环条件

    c)       循环变量值要改变

    变量初始化;

    2、while循环  //先判断 在执行

    循环变量初始化;

    While(循环条件){

    //循环操作块

    //循环变量值改变

    }

    Eg:

             public class test3{

                      public static void main(String[] args){

                       //求和1-100

                      int i=1;

                      int sum=0;

                      while(i<=100){

                                sum=sum+i;

                                i++;

                      }

                       System.out.println(sum);

             }

    }

    3、 do-while循 //先执行 在判断

    循环变量初始化;

    do{

    //循环操作块

    //循环变量改变

    }while(循环条件);

    Eg:

    public class test4{

             public static void main(String[] args){

             //求和1-100

             int i=0;

             int sum=0;

             do{

             sum=sum+i;

             i+=1;

             }while(i<=100);

                       System.out.println(sum);

             }

    }

    4、for循环   //先判断 在执行 可读性比while循环强

                For(循环变量初始化;循环条件;循环变量改变){

                                //循环操作块

    }

    Eg:

    public class test2{

             public static void main(String[] args){

             //求和1-100

             int sum=0;

             for(int i=1;i<=100;i++){

                       sum=sum+i;     

             }

             System.out.println(sum);

             }

    }

    5、循环使用循序推荐

    1)  如果明确知道循环次数,优先选择for循环

    2)  在不知道循环次数,需要先判断在执行时,选择white循环

    3)  在不知道循环次数,需要先判断在执行时,选择do-while循环

  • 相关阅读:
    oracle 例外
    Help with Intervals(集合的交并补,线段树)
    Mex(线段树的巧妙应用)
    hdu4578Transformation(线段树多个lz标记)
    Coder(线段树)
    Ice-cream Tycoon9(线段树)
    Partition(线段树的离线处理)
    ACM学习大纲(转)
    Codeforces Round #250 (Div. 1)
    记次浙大月赛 134
  • 原文地址:https://www.cnblogs.com/dopaer/p/6473839.html
Copyright © 2020-2023  润新知