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?
something like this ?
for(int i=0; i<10; i++){
   if(input wrong){
     i=i-1;
   }
}
                        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.
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);
  }
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With