Reputation: 6450
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.
Upvotes: 3
Views: 322
Reputation: 837
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.
Upvotes: 1
Reputation: 870
[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!
}
}
}
Upvotes: -2
Reputation: 31184
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.
Upvotes: 9