简体   繁体   English

如何在 Java 中将我的代码从 while 循环更改为 do while 循环

[英]How would I change my code from a while loop to a do while loop in Java

public class Number {
public static void main(String[] args) {
    int start = 45; 
    int stop = 175;
    int count = 0; 
    while (start++ < stop) { 
        if (start % 2 == 0) { 
            count++;// adds one to count
            System.out.println("Found even number " + start);

        }

        if (count == 15) break;
    }

}

This is my current code right now I and I am not sure how to convert this While loop into a Do While loop.这是我现在的当前代码,我不确定如何将此 While 循环转换为 Do While 循环。

I believe you just would have to do:我相信你只需要这样做:

do
{
// code
} while (++start < stop);

Hope it helps.希望能帮助到你。

Your existing condition has a side effect.您现有的状况有副作用。 You have to ensure this happens before each loop iteration.您必须确保在每次循环迭代之前发生这种情况。

start++;
do {
  // Existing body.
} while (start++ < stop);

Also, note that this only works because the guard condition is initially true, so the loop always iterates at least once.另外,请注意,这仅在保护条件最初为真时才有效,因此循环始终至少迭代一次。 If you couldn't guarantee that, you need to use something like the following to make them equivalent, since a do/while loop always executes at least once:如果你不能保证,你需要使用类似下面的东西来使它们等效,因为 do/while 循环总是至少执行一次:

if (start++ < stop) {
  do {
    // Existing body.
  } while (start++ < stop);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM