for loop without index declaration

21,257

Solution 1

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

Solution 2

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

while (space > 0)
{
    // Code

    space--;
}
Share:
21,257
zetologos
Author by

zetologos

Updated on August 20, 2020

Comments

  • zetologos
    zetologos over 3 years

    So I declare a variable some where and initialize it. Now later on I need to use it to loop while its still positive so I need to decrement it. To me looping using a condition and a decrement calls for a for but for it we are missing the first part the initialization. But I don't need to initialize anything. So how do I go about that in a nice way.

    for (space = space; space > 0; space--)//my first way to do it but ide doesnt like it
    

    Second way:

    for (; space > 0; space--)//my friend recommended me this way but looks kind weird
    

    Are there more ways for me to have a loop with only condition and increment/decrement?

    P.S spell check doesn't know that "decrement" is a word. I'm pretty sure it is...

  • Jon Skeet
    Jon Skeet over 12 years
    The post-decrement here will happen before the first body, so the loop will never see it in its "original" value, if you see what I mean.
  • Abdullah Jibaly
    Abdullah Jibaly over 12 years
    Yep, fixed accordingly. It can be useful though in the original form if you just want to make sure the condition is satisfied. Thanks for the correction.
  • zetologos
    zetologos over 12 years
    @JonSkeet But a pre-decrement would fix that. Right?
  • Abdullah Jibaly
    Abdullah Jibaly over 12 years
    No Jon is saying you'll never see the first value of space (if you need it).
  • Jon Skeet
    Jon Skeet over 12 years
    @AbdullahJibaly: The way you've got it, the "..." would still never see the original value of space. The "..." needs to be before space--.
  • zetologos
    zetologos over 12 years
    Well I want the original value for the first run. So wouldn't this work while (--space > 0) ...
  • Abdullah Jibaly
    Abdullah Jibaly over 12 years
    No it wouldn't. Of course if you liked that approach you can change your condition to (--space >= 0) and then take that into account in your body.