Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Restart current iteration in 'for' loop java

Tags:

java

for-loop

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?

like image 994
Killerpixler Avatar asked Oct 26 '12 15:10

Killerpixler


3 Answers

something like this ?

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

}
like image 138
PermGenError Avatar answered Nov 02 '22 09:11

PermGenError


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.

like image 37
Ina Avatar answered Nov 02 '22 07:11

Ina


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);
  }
like image 5
Mik378 Avatar answered Nov 02 '22 08:11

Mik378