[英]Can I run a while loop inside a for loop? [Java] If so, how would I do it in this scenario?
[英]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;
}
}
这是我现在的当前代码,我不确定如何将此 While 循环转换为 Do While 循环。
我相信你只需要这样做:
do
{
// code
} while (++start < stop);
希望能帮助到你。
您现有的状况有副作用。 您必须确保在每次循环迭代之前发生这种情况。
start++;
do {
// Existing body.
} while (start++ < stop);
另外,请注意,这仅在保护条件最初为真时才有效,因此循环始终至少迭代一次。 如果你不能保证,你需要使用类似下面的东西来使它们等效,因为 do/while 循环总是至少执行一次:
if (start++ < stop) {
do {
// Existing body.
} while (start++ < stop);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.