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

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

问题描述

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

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

我发现一个简单的条件,使用while循环比循环更好

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

如果我必须使用我的程序中的计数器值然后我认为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循环的情况

推荐答案

一个主要区别是循环最适合在您不知道需要执行的迭代次数的情况下。如果您在进入循环之前知道这一点,则可以使用进行循环。

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循环而不是循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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