java 如何将(for 循环)转换为(do-while)循环?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10504073/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 01:19:56  来源:igfitidea点击:

How to convert (for loop) to (do-while) loop?

javado-while

提问by Mushfiqur rahman Sajid

This is the question of the book-Introduction to java BY Y Daniel liang.

这是Y Daniel liang 的《Java 简介》一书的问题。

The question is:- 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; 

Please see my coding below. and what modification is needed. Actually I am pretty much confused on how to convert it to DO-WHILE Loop.

请参阅下面的我的编码。以及需要什么修改。实际上,我对如何将其转换为 DO-WHILE 循环感到非常困惑。

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); 
    }
}

回答by Marc

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);

回答by Horonchik

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);