I'm writing a program to implement an algorithm I found in the literature. In this algorithm, I need a while loop;
while(solution has changed){
updateSolution();
}
to check if the while condition is satisfied, I have created an Object (of the same type as solution) called copy. This copy is a copy of the solution before the solution is updated. So if there's been a change in the solution, the condition in the while loop is satisfied.
However, I am having some problems finding the best solution for the conditions of both objects as the while loop is executed, since I start with an empty solution (resultset) and the copy is also empty at that time (both called with the constructor of the class). This means that when the while loop is executed, both objects are equal and thus all statements in the while loop are not executed.
My solution for now is to create a dummy variable that is set to true before the while loop and is set to false in it. I doubt that this is the best solution, so I'm wondering if there is a standard solution to this problem (some way to force the program to always run the first iteration of the while loop)?
Code as it is now:
SolutionSet solution = new SolutionSet();
SolutionSet copy = new SolutionSet();
boolean dummy = true;
while((!solution.equals(copy)) || dummy){
dummy = false;
copy = solution.copy();
solution.update() // here some tests are done and one object may be added to solution
}
The do-while loop is an exit-condition loop. This means that the body of the loop is always executed first. Then, the test condition is evaluated. If the test condition is TRUE, the program executes the body of the loop again.
You use the continue statement to restart a loop such as the while loop, for loop or for-in loop. If there are nested loops, the continue statement will restart the innermost loop.
The continue statement in Python returns the control to the beginning of the while loop. The continue statement rejects all the remaining statements in the current iteration of the loop and moves the control back to the top of the loop.
With a do while loop the condition is not evaluated until the end of the loop. Because of that a do while loop will always execute at least once.
Use do {} while (condition);
.
You can do that with a do-while
statement:
SolutionSet solution = new SolutionSet();
SolutionSet copy = new SolutionSet();
do {
copy = solution.copy();
solution.update() // here some tests are done and one object may be added to solution
} while (!solution.equals(copy));
While
tests the condition and, if is true, runs the specified code.
There's one construction that's a bit different: Do... While
. It executes some code and, at the end of the block, checks whether some condition is met. For example
do {
this;
that;
that another;
} while (this == true);
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