Killerpixler
Killerpixler

Reputation: 4050

Restart current iteration in 'for' loop java

I have a for loop that asks the user to input a number and then does something with it 10 times

I want a check built in that, if the user enters a non accepted input, the loop should restart its current iteration

For example if the user enters something wrong in round 3, round 3 should be restarted.

How do i do that? is there something like a REDO statement in java?

Upvotes: 11

Views: 34322

Answers (3)

Mik378
Mik378

Reputation: 22191

Prefer avoiding to reassign the i variable, this may lead to confusion.

 for(int i=0; i<10; i++){
      String command = null;
      do{
        command = takeCommandFromInput();
      } while(isNotValid(command));
      process(command);
  }

Upvotes: 5

Ina
Ina

Reputation: 4470

You have a couple of choices here.

Continue The continue statement in Java tells a loop to go back to its starting point. If you're using a for loop, however, this will continue on to the next iteration which is probably not what you want, so this works better with a while loop implementation:

int successfulTries = 0;
while(successfulTries < 10)
{
    String s = getUserInput();
    if(isInvalid(s))
        continue;

    successfulTries++;
}

Decrement This approach seems ugly to me, but if you want to accomplish your task using a for loop, you can instead just decrement the counter in your for loop (essentially, 'redo') when you detect bad input.

for(int i = 0; i < 10; i++)
{
    String s = getUserInput();
    if(isInvalid(s))
    {
        i--;
        continue;
    }
}

I recommend you use a while loop.

Upvotes: 10

PermGenError
PermGenError

Reputation: 46438

something like this ?

for(int i=0; i<10; i++){
   if(input wrong){
     i=i-1;
   }

}

Upvotes: 10

Related Questions