1

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?

Abra
  • 19,142
  • 7
  • 29
  • 41
Greddy
  • 37
  • 4

2 Answers2

2

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

  • The input is repeatedly re-captured inside the do-while
  • All the conditions can be encapsulated inside a function that takes as argument the captured input
  • A single if-else statement can be 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(input)) {
        print("This doesnt meet the condition. Try again!");
        continue;
    } else {
        print("Success");
        break;
    }
} while(true);


//Function signature
private boolean shouldRepeat(final String input){
    //conditions
    //Condition1 OR Condition2 OR Condition3
}
Spyros K
  • 2,480
  • 1
  • 20
  • 37
1

You can read initial input before loop and put the inverted conditions with logical OR in the loops condition

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

The loop will continue for as long as at least one condition is not met - evaluated to false. When all conditions have been met - all of them were true, the loop ends.

Chaosfire
  • 4,818
  • 4
  • 8
  • 23