何时使用while循环而不是循环
我正在学习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
在这种情况下,我发现while循环比for循环更好,因为如果我想在for循环中实现相同,我必须将counter的值赋给另一个变量。
但是当while循环优于for循环时,是否存在任何特定情况
for
循环只是一种特殊的while循环,它恰好处理递增变量。 您可以使用任何语言的while
循环模拟for
循环。 它只是语法糖(除了python,其中for
实际上是foreach
)。 所以不,没有特定的情况,其中一个比另一个好(尽管出于可读性原因for
当你做简单的增量循环时,你应该更喜欢for
循环,因为大多数人都可以很容易地告诉你发生了什么)。
因为可以表现得像:
while(true) { } for(;;) { }
虽然可以表现得像:
int x = 0; while(x < 10) { x++; } for(x = 0; x < 10; x++) { }
在你的情况下,是的你可以像下面这样重写它作为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);
一个主要区别是while
当您不提前知道需要执行的迭代次数时, while
循环最适合。 如果您在进入循环之前知道这一点,则可以使用for
循环。
for
和while
是等价的,只是同一个东西的不同语法。
你可以改变这个
while( condition ) { statement; }
对此:
for( ; condition ; ) { statement; }
另一种方法:
for( init; condition; update) { statement; }
相当于:
init; while(condition) { statement; update; }
所以,只需使用看起来更好,或更容易说话。
当你没有迭代器(通常是计数器)时,while循环通常会更好。
记得,
使用for循环完成的所有操作都可以使用while循环完成,但并非所有while循环都可以使用for循环实现。
什么时候:
While-loops
退出条件与循环次数或控制变量无关时,使用While-loops
FOR:
for-loops
只是编写while循环的一种捷径,而初始化语句,控制语句(何时停止)和迭代语句(每次迭代后如何处理控制因子)。
例如,
基本上for循环只是while循环的简写,任何for循环都可以从以下转换:
for([initialize]; [control statement]; [iteration]) { // ... }
和
[initialize]; while([control statement]) { //Do something [iteration]; }
是一样的。
因为它是有限的,因为当它耗尽元素循环时它将完成循环….
如果条件不满足或循环中断,则可以是无限的
编辑
我的错误… for
可以是无限的……
我觉得应该指出的一点是,当你使用for循环时,你不需要将计数器分配给另一个变量。 例如for(counter=0; counter<10; counter++)
是有效的Java代码。
至于你的问题,当你想要一段代码运行一定次数时,for循环通常会更好,而当代码继续运行的条件更通用时,while循环更好,例如有一个布尔值在代码块中满足特定条件时仅设置为true的标志。
你可以这样做:
int counter; for (counter = 0; counter < 10; ) { //do some task if(some condition){ break; } } useTheCounter(counter);
while循环可以执行的任何操作也可以在for循环中完成,而for循环可以执行的任何操作也可以在while循环中完成。
没有。没有具体的情况比什么while
更好。
他们做同样的事情。
这取决于您在应用其中之一时的选择。
while
循环更灵活,而for
循环更易读,如果这就是你要问的。 如果你想知道哪一个更快 ,那么看看我进行的关于for
和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
嗨,我重复你的代码,因为它是不正确的。 你忘记增加你的计数器,使它保持在0
int counter = 0; while (counter < 10) { //do some task if(some condition){ break; } counter++; } useTheCounter(counter); // method which use that value of counter do some other task