如何强制程序始终运行 while 循环的第一次迭代?
我正在编写一个程序来实现我在文献中找到的算法。 在这个算法中,我需要一个 while 循环;
while(solution has changed){
updateSolution();
}
为了检查 while 条件是否满足,我创建了一个名为 copy 的对象(与解决方案类型相同)。此副本是解决方案更新之前的解决方案副本。因此,如果解决方案发生变化,则 while 循环中的条件得到满足。
但是,在执行 while 循环时,我在寻找两个对象的条件的最佳解决方案时遇到了一些问题,因为我从一个空解决方案(结果集)开始,并且当时副本也是空的(两者都使用构造函数调用类)。这意味着当执行 while 循环时,两个对象相等,因此不会执行 while 循环中的所有语句。
我现在的解决方案是创建一个虚拟变量,在 while 循环之前将其设置为 true,并在其中设置为 false。我怀疑这是最好的解决方案,所以我想知道这个问题是否有标准解决方案(某种方法强制程序始终运行 while 循环的第一次迭代)?
现在的代码:
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
}
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
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
使用
do {} while (条件);
。Use
do {} while (condition);
.您可以使用
do-while
< /a> 声明:You can do that with a
do-while
statement:While
测试条件,如果为 true,则运行指定的代码。有一种结构有点不同:
Do...While
。它执行一些代码,并在块的末尾检查是否满足某些条件。例如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