简体   繁体   English

如何在Java中将此while循环转换为for循环?

[英]How do I convert this while loop to a for loop in java?

given: 给出:

int counter = 10;

while (counter > 0)
{

    System.out.println(counter);
    counter = counter - 1;
}

So far I have: 到目前为止,我有:

for (int i = 0, i < 10, i --){

    int counter = 10
    System.out.println(counter)
}

I don't think that's correct but I can't quite get it. 我不认为这是正确的,但我不太明白。 Any help would be great. 任何帮助都会很棒。 Thanks 谢谢

for (int counter = 10; counter > 0; counter--) {
     System.out.println(counter);
}

Creating two integer variables is unnecessary, lets simply use counter in the loop and printing. 不需要创建两个整数变量,只需在循环中使用计数器并打印即可。

Your loop has three parts: 循环包含三个部分:

  • initializing the index 初始化索引
  • testing the index 测试指数
  • 'stepping' the index “逐步”编制索引

For the while loop these are: 对于while循环,这些是:

  • counter = 10
  • counter > 0
  • counter = counter - 1

For a for loop we have for (initialize, test, step) { ... }` 对于for循环,我们具有for(初始化,测试,步骤){...}`

So substitute the while loop parts into a for loop an you will have your answer. 因此,将while循环部分替换为for循环,您将得到答案。

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

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