14 June 2016

Bài 8: 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:​
PHP:
public class AndroidVn {

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

        
15;
        while (
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:​
PHP:
public class AndroidVn {

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

        
15;
        do {
            
System.out.print(" " i++);
        } while (
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:​
PHP:
public class AndroidVn {

    public static 
void main(String[] args) {
        
int i;
        for (
010i++) {
            
System.out.print(" " i);
        }
        
System.out.println("\n..i = " i);
    }
}
Để hiểu hơn các cấu trúc, các bạn tham khảo thêm
Video của Blog StudyAndShare






Nguồn : Android.vn

0 nhận xét:

Post a Comment

 

BACK TO TOP

Xuống cuối trang