Java中的while循環——通過示例學習Java編程(10)
作者:CHAITANYA SINGH
來源:https://www.koofun.com/pro/kfpostsdetail?kfpostsid=20
在上一個教程中,我們討論了for循環的用法。在本教程中,我們將討論while循環的用法。如前一個教程中所討論的,循環用於重復執行同一組語句,直到某個特定條件滿足後,程序就跳出這個循環。
while循環的語法:
1 2 3 4 |
while (condition)
{
statement(s);
}
|
while循環是如何工作的?
在while循環中,首先評估while後面的括號裏面循環條件,如果評估循環條件返回的值是true(真),則程序繼續執行while循環中的語句。如果評估循環條件返回的值是,程序就跳出循環,執行while循環代碼塊外面的下一個語句。
註意:使用while循環的代碼塊裏面,一定要正確的對循環變量使用遞增或遞減語句,這樣循環變量的值在每次循環時都會更新,當循環變量的值更新到某個值的時候,while後面的循環條件的評估會返回false值(假),這個時候程序就會跳出循環。如果循環變量的值遞增或遞減語句寫得不對,while後面的循環條件永遠都是返回true值,這樣的話程序永遠也不會跳出while循環的代碼塊,這是循環就進入了一個死循環。
while循環示例(簡單版):
1 2 3 4 5 6 7 8 9 |
class WhileLoopExample {
public static void main(String args[]){
int i= 10 ;
while (i> 1 ){
System.out.println(i);
i--;
}
}
}
|
輸出:
1 2 3 4 5 6 7 8 9 |
10
9
8
7
6
5
4
3
2
|
while循環示例(死循環):
1 2 3 4 5 6 7 8 9 10 |
class WhileLoopExample2 {
public static void main(String args[]){
int i= 10 ;
while (i> 1 )
{
System.out.println(i);
i++;
}
}
}
|
在while後面的括號裏面的循環條件是i>1,因為i的初始值是10(>1),在循環代碼裏面又不停地給i的值進行遞增(i++)操作,i的值會越來越大,這樣循環條件(i>1)永遠返回的值都是true(真),所以程序永遠不會跳出這個循環,這個循環是一個死循環。
下面是另一個死循環的示例:
1 2 3 |
while ( true ){
statement(s);
}
|
while循環示例(遍歷數組元素):
在這裏,我們使用while循環來遍歷和顯示數組(array)裏面的每個元素。
1 2 3 4 5 6 7 8 9 10 11 |
class WhileLoopExample3 {
public static void main(String args[]){
int arr[]={ 2 , 11 , 45 , 9 };
//i starts with 0 as array index starts with 0 too
int i= 0 ;
while (i< 4 ){
System.out.println(arr[i]);
i++;
}
}
}
|
輸出:
1 2 3 4 |
2
11
45
9
|
Java中的while循環——通過示例學習Java編程(10)