何时使用 while 循环而不是 for 循环 [英] when to use while loop rather than for loop

查看:27
本文介绍了何时使用 while 循环而不是 for 循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am learning java as well android. Almost everything that we can perform by while loop those things we can do in for loop.

我发现了一个简单的条件,即使用 while 循环优于 for 循环

I found a simple condition where using while loop is better than for loop

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

if i have to use the value of counter in my program then i think while loop is better than for loop

使用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 的值分配给另一个变量.

In this case I found while loop is better than for loop because if i want to achieve the same in for loop i have to assign the value of counter to another variable.

但是有没有什么特定的情况,while循环比for循环好

推荐答案

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

One main difference is while loops are best suited when you do not know ahead of time the number of iterations that you need to do. When you know this before entering the loop you can use for loop.

这篇关于何时使用 while 循环而不是 for 循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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