当前位置:编程学习 > JAVA >>

java的几种循环有啥区别

for while do while 有啥区别

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

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


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



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

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


<?php
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:

<?php
$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:

<?php
$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 <i>least once</i>" criterion pops up its pretty head.

rlynch AT lynchmarks DOT com

上一个:求JAVA远程注册的简易源代码?
下一个:java编程软件在哪里可下载

CopyRight © 2022 站长资源库 编程知识问答 zzzyk.com All Rights Reserved
部分文章来自网络,