何时使用while循环而不是循环

6 java while-loop

我正在学习java以及android.几乎所有我们可以执行的操作都会循环我们可以在while循环中执行的操作.

我找到了一个简单的条件,使用while循环比循环更好

如果我必须在我的程序中使用计数器的值,那么我认为while循环比循环更好

使用while循环

int counter = 0;
while (counter < 10) {
    //do some task
    if(some condition){
        break;
    }
}
useTheCounter(counter); // method which use that value of counter do some other task
Run Code Online (Sandbox Code Playgroud)

在这种情况下,我发现while循环比for循环更好,因为如果我想在for循环中实现相同,我必须将counter的值赋给另一个变量.

但是当while循环优于for循环时,是否存在任何特定情况

Chr*_*rle 14

for环就是一种特殊的while循环,这正好应对递增的变量.您可以for使用while任何语言的循环模拟循环.它只是语法糖(除了python for实际上foreach).所以不,没有特定的情况,其中一个比另一个更好(尽管出于可读性的原因,for当你做简单的增量循环时,你应该更喜欢循环,因为大多数人都可以很容易地知道发生了什么).

因为可以表现得像:

while(true)
{
}

for(;;)
{
}
Run Code Online (Sandbox Code Playgroud)

虽然可以表现得像:

int x = 0;
while(x < 10)
{
    x++;
}

for(x = 0; x < 10; x++)
{
}
Run Code Online (Sandbox Code Playgroud)

在你的情况下,是的你可以像下面这样重写它作为for循环:

int counter; // need to declare it here so useTheCounter can see it

for(counter = 0; counter < 10 && !some_condition; )
{
    //do some task
}

useTheCounter(counter);
Run Code Online (Sandbox Code Playgroud)


小智 13

一个主要的区别是while当你不知道你需要做的迭代次数时,循环最适合.如果在进入循环之前知道这一点,可以使用for循环.

  • 你能举例说明你的答案吗? (2认同)
  • 通常,当从缓冲区逐行读取文件时,您将使用while循环(因为您不知道何时会出现文件结束标记) (2认同)

Paŭ*_*ann 5

for并且while是等价的,只是同一个东西的不同语法.


你可以改变它

while( condition ) {
   statement;
}
Run Code Online (Sandbox Code Playgroud)

对此:

for( ; condition ; ) {
    statement;
}
Run Code Online (Sandbox Code Playgroud)

另一种方法:

for( init; condition; update) {
    statement;
}
Run Code Online (Sandbox Code Playgroud)

相当于:

init;
while(condition) {
    statement;
    update;
}
Run Code Online (Sandbox Code Playgroud)

所以,只需使用哪个看起来更好,或者更容易说话.