简体   繁体   中英

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:

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

For a for loop we have for (initialize, test, step) { ... }`

So substitute the while loop parts into a for loop an you will have your answer.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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