Bài 5: Cấu trúc lặp while, do while, for trong Java!

Dạng 1: while(…)

while(điều_kiện_lặp){
khối_lệnh;
}

Xét điều kiện trước, đúng rồi mới thực hiện khối lệnh. Vd:

public class ViduWhile {
 
    public static void main(String[] args) {
        int i;
        i = 0;
        while (i < 10) {
            System.out.print(" "+i++);
        }
        System.out.println("...i = "+i);
 
        i = 15;
        while (i < 10) {
            System.out.print(" "+i++);
        }
        System.out.println("...i = "+i);
    }
}

Dạng 2: do{…}while;

do{
khối_lệnh;
}while(điều_kiện);

Thực hiện khối lệnh trước, rồi xét điều kiện, nếu sai thì không thực hiện nữa. Như vậy, ngay cả điều kiện sai từ lần đầu, từ khối lệnh luôn được thực hiện ít nhất 1 lần. Vd:

public class ViDuDoWhile {
 
    public static void main(String[] args) {
        int i = 0;
        do {
            System.out.print(" " + i++);
        } while (i < 10);
        System.out.println("...i = " + i);
 
        i = 15;
        do {
            System.out.print(" " + i++);
        } while (i < 10);
        System.out.println("...i = " + i);
    }
}

Dạng 3: for(…)

for(khởi_tạo_biến_đếm;đk_lặp;tăng_biến){
<khối_lệnh>;
}

Vd:

public class AndroidVn {
 
    public static void main(String[] args) {
        int i;
        for (i = 0; i < 10; i++) {
            System.out.print(" " + i);
        }
        System.out.println("\n..i = " + i);
    }
}

Nguồn : android.vn

Nguyễn Linh

Chia sẻ để cùng tiến bộ...