• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

jq+ flow control question

 
Ranch Hand
Posts: 129
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Here is what seems like a straightforward flow question from JQ+:
<pre>
class TestClass
{
public static void main(String args[])
{
boolean b = false;
int i = 1;
do
{
i++ ;
} while (b = !b);
System.out.println( i );
}
}
</pre>
Why is the result 3 instead of 2? I know a do/while loop will always run at least once because it runs the loop before evaluating the condition, but in this case it seems to be running 2 times through?
Or have I been staring at my screen so long that I am missing where else the var is incremented?
Thanks,
Liz

------------------
Elizabeth Lester
SCJP Dreamin'
 
Author & Gold Digger
Posts: 7617
6
IntelliJ IDE Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi Elizabeth,
the first time the body of the do-while loop is executed, i is incremented and has value 2 at the end of the loop. the boolean b is false, thus the condition (b = !b) will yield b=true, thus the condition is true and the loop is executed one more time, and i is incremented a second time. This time (b = !b) yields false and the loop does not execute any more. The resulting value of i is thus 3.
Val
 
Elizabeth Lester
Ranch Hand
Posts: 129
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Right. Assignment, not equality.
Thank you for pointing out my blindness! Arg, I need to not let those get past me.
--liz
 
Valentin Crettaz
Author & Gold Digger
Posts: 7617
6
IntelliJ IDE Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
you're welcome liz...
val
 
Don't get me started about those stupid light bulbs.
reply
    Bookmark Topic Watch Topic
  • New Topic