while循環
- while循環
- do...while循環
- for循環
- 在Java5中引入了一種主要用於數組的增強型for循環
while循環
- while循環是最基本的循環,它的結構為
while(布爾表達式){
//循環內容
}
- 只要布爾表達式為true,循環會一直執行下去。
我們大多數情況是會讓循環停止下來的,我們需要一個讓表達式失效的方式來結束循環。
- 少部分情況需要循環一直執行,比如服務器的請求響應監聽等。
- 循環條件一直為true就會造成無限循環【死循環】,我們正常的業務編程中應該盡量避免死循環。會影響程序性能或造成程序卡死奔潰!
public class WhileDemo01 {
public static void main(String[] args) {
//1 + 2 + 3 + 4 + ......+ 99 + 100
int i = 0;
int sum = 0;
while (i < 100) {
sum = sum + i;
i++;
}
System.out.println(sum);//5050
}
public class WhileDemo02 {
public static void main(String[] args) {
//死循環
while (true){
//等待客戶端連接
//定時檢查
//。。。。。。
}
}
}
public class WhileDemo03 {
public static void main(String[] args) {
//輸出1~100
int i = 0;
while (i < 100) {
i++;
System.out.println(i);
}
}
}
>在人生的漫長戲劇中,我體會不了我自己這角色的意義,因為我並不知道別人扮演什么角色。——《飛鳥集》