Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Efficient way of checking condition within a do while loop?

I am using a Do While loop but i have to test whether that condition is met half way through the loop so that if it is met it will skip that part. Is there an efficient way of doing this?

e.g. I currently have something like this:

do {
    method1;
    if (!condition) 
        method2;
} while (!condition);

EDIT: I apologise, i don't think i made it clear in the first place. The condition starts as being false, and at some point during the loop one of the methods will set the (global) "condition" to true at which point i want the loop to immediately end. I just think it's messy having to test the ending condition of the loop within it and was wondering if there was anything obvious i was missing.

like image 874
brent Avatar asked Dec 30 '25 09:12

brent


1 Answers

Please provide more info about methods. If you can return condition from method1/2, then try:

do {
    method1;
} while (!condition && !method2)

or if you pass by reference and method return always true:

while (method1 && !condition && method2 && !condition);

or:

while (!method1 && !method2);

EDIT: if:

public boolean method1/2 { ... logic ... ; condition = true; return condition;}

it's hardly depend on what you will do.

like image 97
Anton Bessonov Avatar answered Jan 01 '26 21:01

Anton Bessonov