While循環和do…while循環及二者區別
Whlie循環
while是最基本的循環。
語法
While(布爾表達式){
//循環內容
}
重點
- 只要布爾表達式為true,循環就會一直執行下去
- 我們大多數情況下會讓循環停止下來的,我們需要一個讓表達式失效的方式來結束循環
- 少部分情況需要一直執行,比如服務器的請求相應監聽等
- 循環條件一直為true就會造成無限循環【死循環】,我們正常的業務編程要盡量避免死循環。
實例
package com.singer.struct;
public class WhileDemo01 {
public static void main(String[] args) {
// 輸出1-100
int i = 0;
while (i<100){
i++;
System.out.println(i);
}
}
}
package com.singer.struct;
public class WhileDemo02 {
public static void main(String[] args) {
//計算1+2+3+...100=?
int i = 0;
int sum = 0;
while (i<=100){
sum = sum+i;
i++;
}
System.out.println(sum);
}
}
do...while循環
對於while語句來說,如果不滿足條件,則不能進入循環,但有時候我們需要即使不滿足條件,也至少執行一次循環。
Do…while循環和while循環相似,不同的是,do…while循環至少會執行一次。
語法
do{
//代碼語句
}while(布爾表達式)
實例
package com.singer.struct;
public class DoWhileDemo01 {
public static void main(String[] args) {
int i = 0;
int sum = 0;
do {
sum = sum+i;
i++;
}while (i<=100);
System.out.println(sum);
}
}
package com.singer.struct;
public class DoWhileDemo02 {
public static void main(String[] args) {
int a = 0;
while (a>0){
System.out.println(a);
a++;
}
System.out.println("===============");
do {
System.out.println(a);
a++;
}while (a<0);
System.out.println(a);
}
}
While循環和do…while循環的區別
- while先判斷后執行,do…while是先執行后判斷。
- do…while總是保證循環體會被至少執行一次。