• 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 all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Liutauras Vilda
  • Campbell Ritchie
  • Tim Cooke
  • Bear Bibeault
  • Devaka Cooray
Sheriffs:
  • Jeanne Boyarsky
  • Knute Snortum
  • Junilu Lacar
Saloon Keepers:
  • Tim Moores
  • Ganesh Patekar
  • Stephan van Hulst
  • Pete Letkeman
  • Carey Brown
Bartenders:
  • Tim Holloway
  • Ron McLeod
  • Vijitha Kumara

Dan Chisholm Trick Control  RSS feed

 
Ranch Hand
Posts: 30
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I cannot seem to get my brain around this one:
class JMM114 {
public static void main (String[] args) {
int i = 0, j = 0;
while (i++ < 3) do
System.out.print(j);
while (j++ < 3);
}}

Prints: 012345
I can understand why three is printed, but does J continue to be incremented even though the test fails, giving us 4,5?
 
Ranch Hand
Posts: 90
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
There's a difference between while and do, do will be always executed at least once.
Try indenting the code so that it looks like this:

It will continue printing (although j<3) because System.out.print is inside the do...while loop.
HTH,
B.
 
Ranch Hand
Posts: 384
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hey gerald,

the plain text, is all 3 prints from do while, bold print in the do...while means that it has done the do, then failed the second while
the first whiles bold is after the second while failed.
I hope this helps in the explanaition.
Davy
[ March 16, 2004: Message edited by: Davy Kelly ]
 
blacksmith
Ranch Hand
Posts: 979
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi there,
I added some print statements for clarification:

This gives:
i: 0 j: 0 1 2 3
i: 1 j: 4
i: 2 j: 5
I had to doublecheck what I was doing on paper.
Greetings,
Gian Franco
 
Don't get me started about those stupid light bulbs.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!