• Post Reply Bookmark Topic Watch Topic
  • New Topic

help with looping  RSS feed

 
Olaoluwa Odusegun
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I was learning looping in Java and decided to try this code and then I encountered an endless loop of 2s. why is that? Can someone explain to me. I believe this line count=count++ caused it.
 
Knute Snortum
Sheriff
Posts: 4281
127
Chrome Eclipse IDE Java Postgres Database VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Check your braces {}
 
Arthur Vinicius Rebelo
Ranch Hand
Posts: 30
1
Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Use a prefix increment like this : count = ++count. Or even better just count++
 
Knute Snortum
Sheriff
Posts: 4281
127
Chrome Eclipse IDE Java Postgres Database VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It isn't a brace mismatch like I first thought. The problem is the third part of your for loop.
 
Knute Snortum
Sheriff
Posts: 4281
127
Chrome Eclipse IDE Java Postgres Database VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Posted at the same time!
 
Knute Snortum
Sheriff
Posts: 4281
127
Chrome Eclipse IDE Java Postgres Database VI Editor
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
To see what's happening here and why, try this code:



What's the output? Now try this:



Now try this:



Lastly try this:



count++ says "use" the variable and then increment. In count = count++, it will evaluate count, which is two, and then increment it. But then you're setting count to two immediately. Basically, count = count++ is never what you want, just count++ or ++count.
 
Campbell Ritchie
Marshal
Posts: 56562
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Welcome to the Ranch

That is a common error which arises from a misunderstanding about how i++ works.
You will see loops written in books like this:-and like this:-There are good reasons for sticking to the conventional formats, and one of the good reaosns is this:-
Those loops always work
 
Campbell Ritchie
Marshal
Posts: 56562
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
A few minutes ago, I wrote: . . . That is a common error . . .
But I don't remember seeing it in a loop quite like that.
Always keep your loop headings nice and simple. You may come across things like this:That sort of code was popular with C programmers 40 years ago because it is very concise, but it is very difficult to understand, so I won't even bother explaining it. I shall simply tell you to avoid that sort of code, even though it will happily run in Java®.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!