3

Is it possible to mid while loop, return to the beginning of the loop?

Something like this

 while(this is true)
 {
      do stuff...
      if(this is true)
        {
            restart while loop;
        }
  }

Adding clarity: I did not mean restart as in reset variables, I mean restart in the sense of stopping execution and going on to the next iteration.

2
  • 1
    Won't continue; do exactly that? Commented Jul 12, 2012 at 17:34
  • 2
    what do you mean by "restart", reset all variables? Commented Jul 12, 2012 at 17:34

3 Answers 3

9

the continue keyword will do that

while(this is true)
 {
      do stuff...
      if(this is true)
        {
            continue;
        }
  }

Basically, continue stops execution of the loop on the spot, and then goes on to the next iteration of the loop. you can do this with other loops such as for loops too.

Sign up to request clarification or add additional context in comments.

1 Comment

Awesome, exactly what I am looking for.
1

Yes it is possible. Java provides labels for loops or statement blocks and it must precede a statement. Syntax is identifier:

START: while(this is true)
 {
      do stuff...
      if(this is true)
        {
            continue START;
        }
  }


There are many more ways to do this but i consider this the simplest method.

Comments

-2

[EDIT] Misunderstood the question! This works if you want to restart the loop.

There are many ways you can do it. You can have the while loop in a function and call the function. Such as:

public static void loop(){
       while(this is true)  {
              do stuff...
              if(this is true) {
                   loop();
                   break; <-- dont forget this!
              }
       } 
}

4 Comments

Because of infinant looping If you never change any inputs loop() would just keep calling itself and you would be locked into an infinite loop.
This will lead to a StackOverflowError (or similar) in any possible language.
@EricSauer I didn't personally downvote, because You did give an answer to the question that the OP asked(if you take it literally), but I can understand why others would downvote it. You probably didn't answer what the OP meant
and no, it's not guaranteed to be a stack overflow, (but the risk of SO could indeed be high) do stuff... might cause this not to be true, thus not recurring infinitly.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.