同时和比较 [英] do-while and while comparison

查看:161
本文介绍了同时和比较的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

do-while:

do
{ 
    i++; 
    ++j;
    System.out.println( i * j );

}
while ((i < 10) && (j*j != 25));

我正在学习do-while vs目前,并想重写上面的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:

while ((i < 10) && (j*j != 25))
{
    i++;  
    ++j;
    System.out.println( i * j );
}

干杯

推荐答案

do-while 之间的区别 进行比较时。使用 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 循环是退出控制循环,这意味着它在结束时退出。 循环是一个条目控制循环,这意味着条件在开始时被测试,因此循环内的代码可能不会甚至被执行。

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);

在这种情况下,你想要至少询问一次,它通常比使用<$更优雅c $ c> 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.

相反,循环更多公共,可以轻松替换 do-while (并非所有语言都有循环)。

At the opposite, while loops are much more commons and can easily replace a do-while (not all languages have both loops).

这篇关于同时和比较的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆