java的几种循环有啥区别

for while do while 有啥区别
2024-11-15 19:13:40
推荐回答(4个)
回答1:

do-while 和 while 循环非常相似,区别在于表达式的值是在每次循环结束时检查而不是开始时。和正规的 while 循环主要的区别是 do-while 的循环语句保证会执行一次(表达式的真值在每次循环结束后检查),然而在正规的 while 循环中就不一定了(表达式真值在循环开始时检查,如果一开始就为 FALSE 则整个循环立即终止)。

do-while 循环只有一种语法:

$i = 0;
do {
echo $i;
} while ($i > 0);
?>

以上循环将正好运行一次,因为经过第一次循环后,当检查表达式的真值时,其值为 FALSE($i 不大于 0)而导致循环终止。

资深的 C 语言用户可能熟悉另一种不同的 do-while 循环用法,把语句放在 do-while(0) 之中,在循环内部用 break 语句来结束执行循环。以下代码片段示范了此方法:

do {
if ($i < 5) {
echo "i is not big enough";
break;
}
$i *= $factor;
if ($i < $minimum_limit) {
break;
}
echo "i is ok";

/* process i */

} while(0);
?>

如果还不能立刻理解也不用担心。即使不用此“特性”也照样可以写出强大的代码来。

add a note User Contributed Notes
do-while
rlynch at lynchmarks dot com
09-May-2006 05:02
I would not be as pessimistic about the potential uses of the do-while construction, myself. It is just about the only elegant way of coding blocks that must have at least a single pass of execution, and where various assessments can short-circuit the logic, falling through.

Consider the example of prompting a user to input a value for a variable. The code in while() format might be:

$result = null ;
while( $result === null )
{
print "Gimme some skin, bro!> ";
$result = trim( fgets( $stdin ) );
if( $result === '' )
$result = null ;
}
?>

Well, that works. Lets try it in do-while format:

$result = '';
do {
print "Gimme some skin, bro!> ";
$result = trim( fgets( $stdin ) );
}
while( $result === '' );
?>

See how it just "reads better"? You say to yourself, "set up $result, print a message, get a response, and continue do to that while the nincompoop fails to enter anything."

Likewise, that "Advanced C" programming example turns out to be the elegant "no goto" way to run through exceptionally involved pieces of block-logic, with a trivial 'break' able to get one all the way past all the unnecessary code in one fell swoop.

For just about every other 'while()' block application, it shouldn't be used. While() is what we expect, and while() is what we should use ... except when the surprisingly common "but we have to do it at least once" criterion pops up its pretty head.

rlynch AT lynchmarks DOT com

回答2:

do{循环体}while(条件)
先执行循环体,再判断条件,如果条件满足,继续执行,不满足,退出循环,最少执行一次
while(条件){循环体}
先判断条件,满足就执行循环体,不满足退出
for(;;)举例说明:
从1循环到10,然后把1-10打印出来
for(int i=1;i<=10;i++){
System.out.println(i);
}

回答3:

for循环比较直观地给出了循环次数;
while是先判断其后括号中的条件是否满足,满足则执行循环语句,直到条件不满足时停止循环;
do while是先执行一遍循环语句,再判断while后的括号中的条件是否满足,条件满足则再执行循环语句,直到条件不满足时停止循环。

回答4:

do-while是先执行后判断,因此do-while至少要执行一次循环体。而while是先判断后执行,如果条件不满足,则一次循环体语句也不执行。
for(表达式1;表达式2;表达式3) 第一步,计算表达式1的值。第二步,计算表达式2的值。若值为真(非0)则执行循环体一次,否则跳出循环。第三步,计算表达式3的值,转回第二步重复执行