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

I am writing a program to implement an algorithm that 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 true, I created an object (of the same type as the solution) called a copy. This copy is a copy of the solution before the solution is updated. Therefore, if the solution has been changed, 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 executes, since I start with an empty solution (resultet), and the copy is also empty at this time (both are called with the class constructor). This means that when executing the while loop, both objects are equal, and therefore all the statements of the while loop are not executed.

My solution at the moment is to create a dummy variable that is set to true before the while loop and false is set in it. I doubt this is the best solution, so I wonder if there is a standard solution to this problem (somehow make the program always run the first iteration of the while loop)?

Code as of 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 } 
+6
source share
3 answers

Use do {} while (condition); .

+12
source

You can do this with do-while :

 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)); 
+1
source

While checks the condition and, if true, runs the specified code.

There is one design, slightly different: Do... While . It executes some code and, at the end of the block, checks to see if any condition is met. for instance

 do { this; that; that another; } while (this == true); 
+1
source

Source: https://habr.com/ru/post/897606/


All Articles