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

问题描述 投票:-1回答:2
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;
    }

}

这是我当前的当前代码,我不确定如何将While循环转换为Do While循环。

java while-loop do-while
2个回答
0
投票

您的现有状况有副作用。您必须确保在每次循环迭代之前发生这种情况。

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

此外,请注意,这仅是因为保护条件最初为true,所以该循环始终至少迭代一次。如果不能保证,则需要使用如下所示的方法使它们等效,因为do / while循环始终至少执行一次:

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

1
投票

我相信您只需要这样做:

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

希望有帮助。

© www.soinside.com 2019 - 2024. All rights reserved.