Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Puzzling question

 
Jesse Torres
Ranch Hand
Posts: 985
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The following code enters the while loop and immediately increments age. So age�s first print is 13.


However, if I put the increment (age++) below the else statement, the while loop becomes an infinite loop, endlessly printing �Obtain your Drivers License."




Why does it become an infinite loop?

Thanks,
 
Jesse Torres
Ranch Hand
Posts: 985
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I noticed that if I comment out "continue outer" after the first if statement, the while loop behaves fine.



I still don't understand, why the loop with "continue outer" and the increment age++ on the bottom, goes into an infinite loop.

Thanks,
[ May 25, 2005: Message edited by: Jesse Torres ]
 
Roman Tomach
Greenhorn
Posts: 15
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Because after "continue outer" the value of "age" is still 16. So it never be incremented.
 
Jesse Torres
Ranch Hand
Posts: 985
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Roman Tom:
Because after "continue outer" the value of "age" is still 16. So it never be incremented.


That makes sense. Thanks. However, why aren't the values that are less than 16 being printed before age reaches 16 for infinite example?

Thanks,
[ May 25, 2005: Message edited by: Jesse Torres ]
 
Ashok Kumar
Ranch Hand
Posts: 93
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The values less than 16 do print on the screen.Since it enters a infinite loop you might have missed the initial part of it.IF you are viewing the o/p on a command prompt then increse the buffer size and terminate the program and scroll up.
 
Timmy Marks
Ranch Hand
Posts: 226
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Now you know why the JavaRanch style guide forbids the use of continue in the middle of a loop. Can make for some difficult code to understand.
 
Jesse Torres
Ranch Hand
Posts: 985
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you all!
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic