1. 程式人生 > 其它 >java流程控制之迴圈結構: while與do...while

java流程控制之迴圈結構: while與do...while

迴圈結構

java中的迴圈結構:

  • while迴圈

  • do....while迴圈

  • for迴圈

  • 在java5中引入了一種主要用於陣列的增強for迴圈


1.while迴圈:

  • while是最基礎的迴圈
  • 基本語法:

          while(布林表示式){
              //迴圈內容
          }
    
  • 只要布林表示式為true,迴圈就會一直執行下去。

  • 我們大多數情況會讓迴圈停止下來的,我們需要一個讓表示式的方失效式來結束迴圈

  • 少部分情況需要迴圈一直執行,比如伺服器的請求響應監聽等。

  • 迴圈條件一直為true就會造成無限迴圈【死迴圈】,我們正常的業務程式設計中應該儘量避免死迴圈。會影響程式效能或者造成程式卡死奔蹦!

1.1 while迴圈簡單演示:輸出1~100

package struct;

public class WhileDemo02 {

    public static void main(String[] args) {
        //輸出1~100
        int i=0;
        while (i<100){
            i++;
            System.out.print(i+"\t");
        }
    }
}


執行結果

1	2	3	4	5	6	7	8	9	10	11	12	13	14	15	16	17	18	19	20	21	22	23	24	25	26	27	28	29	30	31	32	33	34	35	36	37	38	39	40	41	42	43	44	45	46	47	48	49	50	51	52	53	54	55	56	57	58	59	60	61	62	63	64	65	66	67	68	69	70	71	72	73	74	75	76	77	78	79	80	81	82	83	84	85	86	87	88	89	90	91	92	93	94	95	96	97	98	99	100	

1.2 死迴圈演示:

package struct;

public class WhileDemo03 {
    public static void main(String[] args) {
        //死迴圈

        while (true) {
            //用於等待客戶連線
            //用於定時檢查
            //。。。。。。

        }
    }
}

1.3 while迴圈簡單演示:輸出1~100的和

package struct;

public class WhileDemo01 {
    public static void main(String[] args) {
    //    計算1+2+3+....+100=?


            int a=0;
            int sum=0;
            while (a<100){
                a++;
                sum=a+sum;

            }
            System.out.println(sum);
            
    }
}


執行結果

5050


2.do.....while迴圈:

  • 對於while迴圈語句而言,如果不滿足條件,則不能進入迴圈。但有時候我們需要即使不滿足條件,也至少執行一次。
  • do....while迴圈和while迴圈相似,不同的是,do...while迴圈至少會執行一次

  • 基本語法:

          do{
              //迴圈內容
          }while(布林表示式);
    

  • While和do-while的區別

1. while先判斷後執行,do-while是先執行後判斷!

2. do...while總是保證迴圈體會被至少執行一次!這是他們的主要差別


2.1 do...while迴圈簡單演示:輸出1~100的和

package struct;

public class DoWhileDemo02 {
    public static void main(String[] args) {
        int a=0;
        int sum=0;
        
        do{
           a++;
           sum=a+sum;
        }while (a<100);

        System.out.println(sum);

    }
}

執行結果

5050

2.2 while和do...while的區別演示:

package struct;

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

        int a=0;
        while (a<0){
            System.out.println(a);
            a++;
            
        }
        System.out.println("=============");//如果等號上無內容列印,充分說明do..while至少迴圈一次
        
        do {
            System.out.println(a);
            a++;
        }while (a<0);
        
    }
    
}


執行結果

=============
0


3. 更多參考

狂神說Java