是不是可以在一个while循环被中断后重新进入它?

huangapple go评论57阅读模式
英文:

Is it possible to reenter a while loop after it has been broken out of?

问题

Sure, here are the translated parts:

当我在while循环的末尾设置一个"break;"语句,或者当它的条件设置为false时,有没有办法回到循环的顶部再次执行它?

我知道"continue;"语句。它会跳回到while循环的顶部,但只有在它在该循环内声明时才有效。

在完全退出循环后,是否有一种方法实现相同的效果?

while(true) {
    //代码
    break;
}

int i=1;

if(i=1) {
    //命令返回到while循环中
}
英文:

So when I set a "break;" statement at the end of a while loop, or when it's condition is set to false, is there any way to jump back to the top of the loop and go through it once again?

I know of the "continue;" statement. It jumps back to the top of the while loop, but only when it is declared inside of that loop.

Is there some way of achieving the same effect after exiting the loop completely?

while(true) {
	//code
	break;
}

int i=1;

if(i=1) {
	//command to go back into the while loop
}

答案1

得分: 1

这似乎是你可以通过将你的代码分成方法并重用它们来解决的问题?

void executeLoop() {
    while(true) {
        //代码
        break;
    }
}

void doStuff() {
    executeLoop();
    int i=1;

    if(i==1) { // 在这里添加了一个=符号来比较而不是赋值
        executeLoop();
    }
}
英文:

This seems like something you could solve by splitting your code into methods and reusing them?

void executeLoop() {
    while(true) {
        //code
        break;
    }
}

void doStuff() {
    executeLoop();
    int i=1;

    if(i==1) { // Added a = symbol here to compare instead of assigning
        executeLoop();
    }
}

答案2

得分: -2

尝试这个。
你可以使用goto()标签,并在循环顶部添加一个标签。

标签:
While循环
goto标签;

英文:

Try this.
You can use goto() label and add a label at the top of the loop.

label:
While loop
goto label;

huangapple
  • 本文由 发表于 2020年7月23日 03:40:57
  • 转载请务必保留本文链接:https://go.coder-hub.com/63041992.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定