天天看點

4. 循環語句

循環語句

1. while語句

package com.lin.study.xunhuan;

public class WhileDemo {
    public static void main(String[] args) {
        //計算1+2+3+...+100=?
        int i = 0,sum = 0;

        while(i<=100){
            sum = sum + i;
            i++;
        }

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

運作結果:

sum=5050

Process finished with exit code 0

2. do...while語句

do...while語句,至少會執行一次。

package com.lin.study.xunhuan;

public class DoWhileDemo {
    public static void main(String[] args) {
        //計算1+2+3+...+100=?
        int i = 0,sum = 0;

        do{
            sum = sum + i;
            i++;
        }while(i<=100);

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

3. while語句 與 do...while語句 的對比

package com.lin.study.xunhuan;

public class Demo {
    public static void main(String[] args) {
        //對比while與do...while
        int a = 0;

        while(a<0){
            a++;
            System.out.println(a);
        }

        System.out.println("-----------------------------------");

        do{
            a++;
            System.out.println(a);
        }while(a<0);
    }
}      
1