作者:CHAITANYA SINGH
来源:https://www.koofun.com/pro/kfpostsdetail?kfpostsid=22&cid=0
在上一篇教程中,我们讨论了while循环。在本教程中,我们将讨论java中的do-while循环。do-while循环类似于while循环,但是它们之间有一个区别:在while循环中,循环条件在循环的主体执行之前进行评估,而在do-while循环中,循环条件在循环的主体执行之后再进行评估。
do-while循环的语法:
1
2
3
4
|
do { statement(s);
} while (condition);
|
do-while循环是如何工作的?
do-while循环首先执行循环体内的语句,在执行完循环体内的语句后再评估循环条件,如果评估循环条件后返回的值是true,则程序回到do-while循环体里面最上面的语句,开始下一轮循环执行。如果评估循环条件后返回的值是false,程序就会跳出do-while循环体,执行do-while循环体外面的下一个语句。
do-while循环示例
1
2
3
4
5
6
7
8
9
|
class DoWhileLoopExample {
public static void main(String args[]){
int i= 10 ;
do {
System.out.println(i);
i--;
} while (i> 1 );
}
} |
输出:
1
2
3
4
5
6
7
8
9
|
10 9 8 7 6 5 4 3 2 |
do-while循环示例(遍历数组)
这个例子里,我们有一个整型数组,我们使用do-while遍历和显示数组里面的每个元素。
1
2
3
4
5
6
7
8
9
10
11
|
class DoWhileLoopExample2 {
public static void main(String args[]){
int arr[]={ 2 , 11 , 45 , 9 };
//i starts with 0 as array index starts with 0
int i= 0 ;
do {
System.out.println(arr[i]);
i++;
} while (i< 4 );
}
} |
输出:
1
2
3
4
|
2 11 45 9 |