如何将此while循环转换为java中的for循环?

时间:2018-05-02 00:34:30

标签: java loops

给出:

int counter = 10;

while (counter > 0)
{

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

到目前为止,我有:

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

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

我不认为这是正确的,但我不能完全理解。任何帮助都会很棒。感谢

2 个答案:

答案 0 :(得分:3)

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

不需要创建两个整数变量,只需在循环中使用计数器并打印即可。

答案 1 :(得分:1)

你的循环有三个部分:

  • 初始化索引
  • 测试索引
  • &#39;步进&#39;指数

对于while循环,这些是:

  • counter > 0
  • counter = counter - 1
  • ggplot2

对于for循环,我们有     for(initialize,test,step){ ... }`

因此,将while循环部分替换为for循环,您将获得答案。