• Post Reply Bookmark Topic Watch Topic
  • New Topic

Java "math" ?  RSS feed

 
Paul Maxfield
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Sorry this may seem like a really dumb question but could someone explain to me how this works:

This is the code example I wrote from the book I'm studying:



The code out put is:

Before the Loop
In the Loop
Value of x is 1
In the Loop
Value of x is 2
In the Loop
Value of x is 3
This is after the loop


Now I understand where the 1 comes from but I don't understand where the 2 and 3 come from. The answer is probably so simple I'm missing it.
[edit]Add code tags. CR[/edit]
[ November 27, 2008: Message edited by: Campbell Ritchie ]
 
Maneesh Godbole
Bartender
Posts: 11445
18
Android Eclipse IDE Google Web Toolkit Java Mac Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Paul Maxfield:
.. but I don't understand where the 2 and 3 come from. The answer is probably so simple I'm missing it.


It is because of this line


As you know, while loops will continue iterating as long as the condition specified evaluates to true (x<4) in your case.
So for the first iteration you get
x=1 so x<4 is true
For the second you get (since you are incrementing x's value by 1)
x=2 so x<4 is true
For the third you get
x=3 so x<4 is true
After that x becomes 4 and x<4 is false. So the control exits the while loop and you get the "This is after the loop".

Sorry this may seem like a really dumb question

Don't worry about this. I still confuse the pre-increment and post-increment operators sometimes
[ November 26, 2008: Message edited by: Maneesh Godbole ]
 
Campbell Ritchie
Marshal
Posts: 56518
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Paul Maxfield:
Sorry this may seem like a really dumb question . . .


I trust Maneesh's explanation is satisfactory?

That is not a dumb question at all.
 
Gamini Sirisena
Ranch Hand
Posts: 378
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Paul,
As you said, where does the 1 come from?
 
Maneesh Godbole
Bartender
Posts: 11445
18
Android Eclipse IDE Google Web Toolkit Java Mac Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Gamini Sirisena:
Paul,
As you said, where does the 1 come from?


From here
 
Paul Maxfield
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ah....now I get it, thank you very much
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!