Java 笔记整理(二)for循环、while循环、do - while循环的区别

时间:2021-01-20 20:26:18

RT

    隔壁的小弟,也去培训机构培训java。昨晚他问我for,while,do-while循环的区别和联系。说是说出来了,可是不是特别快,所以还是整理下记下,以后好复习。public class ForWhileDowhile {
       /**       * i的i次方和       * for循环、while循环、do -while循环的区别       * for语句和while语句先判断条件,后执行语句,do -while语句则是先执行语句判断在判断条件,因此do -while语句的循环体至少执行一次       * 必须在while和do -while语句之前对循环体变量赋处置,而for�Z句可在表�_式中�循�h�量�x初值       * 在循�h次�狄呀��_定的情�r下,通常用for�Z句;而��於循�h次�挡淮_定只�o出循�h�Y束�l件的���},通常用while�Z句解�Q       * @param args       */       public static void main(String[] args) {             // TODO Auto-generated method stub             For();             While();             Dowhile();      }       //for�Z句       public static void For() {             int s=0;             for (int i = 1; i <= 10; i ++) {                   int k=1;                   for (int j = 1; j <= i ; j++) {                        k = k* i;                  }                  s = s + k;            }            System. out.println("for�Z句: s= " + s);      }       //while�Z句       public static void While() {             int i=1,j=0,n=10,s=0;             while (i<=n) {                   int k=1;j=1;                   while ( j<=i ) {// 求出 i 的 i次方的值                        k=k*i;                        j=j+1;                  }                  i=i+1;                  s = s + k;            }            System. out.println("while�Z句: s= " + s);      }       //dowhile�Z句       public static void Dowhile() {             int i=1,j=0,n=10,s=0;             do {                   int k=1;                  j=1;                   do {                        k=k*i;                        j=j+1;                  } while (j<=i);                  i=i+1;                  s=s+k;            } while (i<=n);            System. out.println("dowhile�Z句: s= " + s);      }}