do-while 和 while 比较 [英] do-while and while comparison
问题描述
同时进行:
do
{
i++;
++j;
System.out.println( i * j );
}
while ((i < 10) && (j*j != 25));
我目前正在学习 do-while 与 while,并想改用 while 重写上述 java 片段(已声明和初始化).以下重写的代码是否正确:
I am learning about do-while vs while at the moment and would like to rewrite the above java fragment (already declared and initialized) using a while instead. Are the below rewritten codes correct way to do so:
同时:
while ((i < 10) && (j*j != 25))
{
i++;
++j;
System.out.println( i * j );
}
干杯
推荐答案
do-while
和 while
的区别在于 when比较完成.使用 do-while
,您将在最后进行比较,因此至少进行一次迭代.
The difference between a do-while
and a while
is when the comparison is done. With a do-while
, you'll compare at the end and hence do at least one iteration.
do
{
i++;
++j;
System.out.println( i * j );
}
while ((i < 10) && (j*j != 25));
相当于:
i++;
++j;
System.out.println( i * j );
while ((i < 10) && (j*j != 25)) {
i++;
++j;
System.out.println( i * j );
}
一般理解
do-while
循环是一个退出控制循环,这意味着它在最后退出.while
循环是一个入口控制循环,这意味着在开始时测试条件,因此,循环内的代码甚至可能不会被执行.>
General comprehension
A do-while
loop is an exit controlled loop which means that it exits at the end. A while
loop is an entry controlled loop which means that the condition is tested at the beginning and as a consequence, the code inside the loop might not even be executed.
do {
<block>
} while (<condition>);
相当于:
<block>
while (<condition>) {
<block>
};
用例
do-while
的一个典型用例如下:你问用户一些事情,你想在输入不正确时重复操作.
Use case
A typical use case for a do-while
is the following: you ask the user something and you want do repeat the operation while the input is not correct.
do {
// Ask something
} while (input is not correct);
在这种情况下,您至少要询问一次,它通常比使用 while
更优雅,后者需要复制代码,或添加额外条件或设置任意值第一次强制进入循环.
In that case, you want to ask at least once and it's usually more elegant than using a while
which would require either to duplicate code, or to add an extra condition or setting an arbitrary value to force entering the loop the first time.
相反,while
循环更为常见,可以轻松替换 do-while
(并非所有语言都有这两种循环).
At the opposite, while
loops are much more commons and can easily replace a do-while
(not all languages have both loops).
这篇关于do-while 和 while 比较的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!