循环结构 :do-while

循环结构 :do-while

循环四要素:
  1.初始化条件
  2.循环条件
  3.循环体
  4.迭代条件

格式:
    1.初始化条件
    do{
      3.循环体
      4.迭代条件
    }while(2.循环条件);

public class DoWhileTest{

    public static void main(String[] args){
    
        //需求 :求100以内的奇数,求奇数的个数,求奇数的总和
        int i = 1;//初始化条件
        int sum = 0; //奇数的总和
        int count = 0; //奇数的个数
        do{

            //循环体
            if(i % 2 != 0){
                sum += i;
                count++;
                System.out.println(i);
            }

            //迭代条件
            i++;
            
        }while(i <= 100);//循环条件

        System.out.println("count=" + count + " sum=" + sum);
    }
}

do-while和while的区别?

public class DoWhileTest2{

    public static void main(String[] args){
        
        boolean boo = false;

        while(boo){
            System.out.println("while");
        }

        do{
            System.out.println("do-while");
        }while(boo);
    
    }
}
原文地址:https://www.cnblogs.com/zmy-520131499/p/11066479.html