[英]How to convert for loop to do-while loop?
This is a question from the book Introduction to Java by Y Daniel Liang:这是 Y Daniel Liang 的《 Java 简介》一书中的一个问题:
Convert for loop statement to a while loop and do-while loop?将for循环语句转换为while循环和do-while循环?
int sum = 0; for (int i = 0; i <= 7; i++) sum = sum + i;
I am pretty confused on how to convert it to a do-while loop.我对如何将其转换为 do-while 循环感到非常困惑。 What am I supposed to do?我应该做些什么? Please see my code below.请在下面查看我的代码。
public class Convert_forLoop_toWhileLoop {
public static void main(String[] args) {
int sum = 0;
int i = 0;
do {
sum = sum + i;
System.out.println(sum);
i++;
} while(i <= 7);
}
}
Depending on how scrupulous you wanna be, a "more" equivalent do
- while
-loop of your for
-loop example would be:根据您想要的谨慎程度,您的for
循环示例的“更多”等效do
- while
-loop 将是:
int sum1(int n) {
int sum = 0;
for (int i = 0; i <= n; i++) {
sum = sum + i;
}
return sum;
}
int sum2(int n) {
int sum = 0;
{
int i = 0;
if (i <= n) {
do {
sum = sum + i;
i++;
} while (i <= n);
}
}
return sum;
}
Note I wrapped your example in sum1
(passing sum1(7)
is equivalent to your case).注意我将您的示例包装在sum1
(通过sum1(7)
相当于您的情况)。
For those who really want to split hairs -- note Java doesn't necessarily compile the 2 functions above into the same bytecode (at least when I tested it, to my surprise).对于那些真正想要拆分头发的人——请注意,Java 不一定会将上面的 2 个函数编译成相同的字节码(至少在我测试时,令我惊讶的是)。 2 extra bytecode instructions for sum2
(20 vs. 22). sum2
2 个额外字节码指令(20 对 22)。 Just something interesting I noticed.只是我注意到了一些有趣的事情。
Like this:像这样:
int sum = 0;
int i = 0;
do {
sum += i;
i++;
} while (i <= 7);
System.out.println("The sum of 0 thru " +i + " is:" + sum);
Your answer doesnt support the case where i initial value is >= number of loops.您的回答不支持 i 初始值 >= 循环次数的情况。
you need to first check the condition.您需要先检查条件。
while (i <= 7) {
sum+=i;
// at the last statement increase i
i++
}
System.out.println(sum);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.