for loop without index declaration

£可爱£侵袭症+ 提交于 2019-12-02 05:25:29
Alex

another way is this one:

Integer i = 10;
while(--i>0) {
    System.out.println(i);
}

When i is 0 while condition is false... so.. it will print from 9 to 1 (9 items)

Integer i = 10;
while(i-->0) {
    System.out.println(i);
}

Will print from 9 to 0... (10 items);

The latter way is reasonable. An alternative - if you don't have any break/continue statements - would be:

while (space > 0)
{
    // Code

    space--;
}

In my opinion, this is a proper way to go. You might work with iterators that are able to move both forward and backward, but this doesn't necessarily all value to your code.

Use a while loop?

while (space > 0) { /* code */ space--; }

If you don't need the value of space in the body of the loop:

while (space-- > 0) { /* code */ }

When you're writing code, you should always remember that you're not just writing it so that you can understand it now... it should be understandable to any future reader (which might be you after you've forgotten why you did it the way you did) as long as they have some coding knowledge. It seems to me that you might be trying to re-use your space variable just because you already have one. There's nothing wrong with starting a new one if it increases readability. So you might want to consider using int i = space; inside your for loop - I'm sure your computer will manage this without the stack overflowing, if you'll forgive my lousy pun ;-)

In fact, consider refactoring your loop to a separate private method, appropriately named for readability of course, passing in space as an argument and setting the variable to the result you return. Happy to give you a code example if you explain what you're trying to achieve in your loop.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!