如何在满足条件后从循环中断开 [英] How to break from a loop after the condition is met

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

问题描述

我一直试图在过去一小时内摆脱这个循环并继续,因为已经满足了我的条件一次。我的应用程序几乎读取了一系列行并分析它然后打印所述的变量。线条外观如何(不包括。):

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 print c

  • 40 goto 20

  • 50结束

  • 10 c = 9+3
  • 20 a = c+1
  • 30 print c
  • 40 goto 20
  • 50 end

它做的一切正确,当它到达第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天全站免登陆