Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

MixFor5 question about the use of x++ and x-- in a loop  RSS feed

 
Eddie Davis
Greenhorn
Posts: 16
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Why is it that the code x = x++ seems to never get implemented in the code snippet below. I can even change it to x = x-- and I get the same answer 6 14
At some point shouldn't the value get increased by 1 or in the reverse get decreased by 1 when running through the loop?

The previous conversations about the problem MixFor5 has been extremely useful and helped me work through the problems and understand what the code was doing , but I still couldn't figure out the above question. Just for reference below is the link to the other conversations. http://www.coderanch.com/t/410474/Beginning-Java/java/head-first-java-mixed-messages#2070028
Thanks to anyone that could answer my question.

 
Jaydeep Vaishnav
Greenhorn
Posts: 16
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Use x--. It is self explanatory for x=x-1. x=x-- is not the way to use it.
 
Rob Spoor
Sheriff
Posts: 21092
85
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
x++ and x-- work as follows:
1) read the current value of x
2) increment or decrement x
3) return the value from step 1

You are most definitely increasing x - only to assign it its old value immediately after. Also read http://faq.javaranch.com/java/PostIncrementOperatorAndAssignment
 
Campbell Ritchie
Marshal
Posts: 55717
163
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Don't ask the same question twice; I have deleted your other post which was on an old thread because you have replies here.

If you search for "postincrement" you find this question is very frequent. i = i++ is commonly used to confuse beginners. Look at this thread and this one.
 
Eddie Davis
Greenhorn
Posts: 16
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you! I understand now the uses and difference between ++x and x--. I also looked the correct method of posting. Thank you Campbell.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!