java循环有哪几种_java的几种循环有啥区别

满意答案

00e27ab806e4881f8254fe7ae8741834.png

xanewnet

2014.08.20

00e27ab806e4881f8254fe7ae8741834.png

采纳率:55%    等级:10

已帮助:470人

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

00分享举报

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值