Home > Mobile >  While loop strategy with multiple conditionals inside
While loop strategy with multiple conditionals inside

Time:10-07

I am looking for advice on how to write a while loop with a multiple conditionals. The main idea is that we have conditions which are checked and if they don't meet the requirements, they are repeated. For example, we need to enter some input (Numeric String with two numbers). Input has to be numeric, has to be no less than 3 and has to have the same numbers. If whichever condition is not met, it informs the user and ask for the input again. If input matches all the requirements, the loop stops. What is the best scenario for that? My idea was something like that:

while (true) {
    if (!(someMethod)) {
        print("This doesnt meet the condition. Try again!");
        continue;
    }
}

continue does the job of repeating the condition "anew", but I am not sure about what would be the best way to exit the loop?

CodePudding user response:

The input capture use case you describe seems suitable for a do-while loop.

  • The input is captured inside the do-while
  • All your condition are encapsulated inside a function that takes as argument the captured input
  • A single if-else statement is used that makes sure that the loop either repeats with a continue if conditions are not met or ends with a break.
do {
    final String input;    //Code that gets input
    //shouldRepeat should include all conditions
    if (shouldRepeat(string)) {
        print("This doesnt meet the condition. Try again!");
        continue;
    } else {
        print("Success");
        break;
    }
} while(true);


//Function signature
private boolean shouldRepeat(string){
    //conditions
    //Condition1 OR Condition2 OR Condition3
}

CodePudding user response:

You can just put the conditions with logical OR in the loops condition

while(!condition1() || !condition2() || !condition3()) {
  //inform input is not valid
  //read next input
}
  • Related