满足条件后如何跳出循环 [英] How to break from a loop after the condition is met

查看:46
本文介绍了满足条件后如何跳出循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

过去一个小时我一直在尝试打破这个循环并继续,因为已经满足我的条件一次.我的应用程序几乎读取一系列行并对其进行分析,然后打印所述变量.线条的外观示例(不包括 .):

Hi I have been trying for the past hour to break from this loop and continue since already met my condition once. My application pretty much reads a serie of lines and analyzes it and then prints the variable stated. An example of how the lines look like (the . are not included):

  • 10 c = 9+3
  • 20 a = c+1
  • 30 打印 c
  • 40 转到 20
  • 50 结束

它一切正常,当它到达第 40 行时按预期转到第 20 行,但我希望它转到第 50 行,因为它已经去过第 40 行一次.这是我的这部分代码:

It does everything right, when it gets to line 40 goes to line 20 as expected, but i want it to go to line 50 since already went to line 40 once. Here is my code for this part:

while(booleanValue)
{
    if(aString.substring(0, 4).equals("goto"))
    {
        int chosenLine = Integer.parseInt(b.substring(5));
        if(inTheVector.contains(chosenLine))
        {
            analizeCommands(inTheVector.indexOf(chosenLine));
            i++;
        }
        else
        {
            System.ou.println("Line Was Not Found");
            i++;
        }
    }

    else if(aString.substring(0, 3).equals("end"))
        {
            System.out.println("Application Ended");
            booleanValue = false;
        }
}

推荐答案

使用 break 语句可以在满足条件后完全跳出循环.Pol0nium 建议使用 continue 是不正确的,因为这只会停止循环的当前迭代.

Use the break statement to break out of a loop completely once your condition has been met. Pol0nium's suggestion to use continue would not be correct since that stops the current iteration of the loop only.

while(foo)
{
    if(baz)
    {
        // Do something
    }
    else
    {
        // exit condition met
        break;
    }
}

所有这一切都说了,好的形式表明您需要干净的入口和出口点,以便观察者(可能是您自己,在以后重新访问代码)可以轻松地遵循其流程.考虑更改控制 while 循环本身的布尔值.

All this having been said, good form dictates that you want clean entry and exit points so that an observer (maybe yourself, revisiting the code at a later date) can easily follow its flow. Consider altering the boolean that controls the while loop itself.

while(foo)
{
    if(baz)
    {
        // Do something
    }
    else
    {
        // Do something else
        foo = false;
    }
}

如果由于某种原因,您无法触摸控制 while 循环的布尔值,则只需将条件与专门用于控制 while 的标志复合即可:

If, for some reason, you can't touch the boolean that controls the while loop, you need only compound the condition with a flag specifically to control your while:

while(foo && bar)
{
    if(baz)
    {
        // Do something
    }
    else
    {
        // Do something else
        bar = false;
    }
}

这篇关于满足条件后如何跳出循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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