开发者

How to force the program to always run the first iteration of a while loop?

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){
   dumm开发者_开发问答y = false;
   copy = solution.copy();
   solution.update() // here some tests are done and one object may be added to solution
}


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);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜