Win a copy of Spring in Action (5th edition) this week in the Spring forum!
  • 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:
  • Campbell Ritchie
  • Bear Bibeault
  • Devaka Cooray
  • Liutauras Vilda
  • Jeanne Boyarsky
Sheriffs:
  • Knute Snortum
  • Junilu Lacar
  • paul wheaton
Saloon Keepers:
  • Ganesh Patekar
  • Frits Walraven
  • Tim Moores
  • Ron McLeod
  • Carey Brown
Bartenders:
  • Stephan van Hulst
  • salvin francis
  • Tim Holloway

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
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
 
my overalls have superpowers - they repel people who think fashion is important. Tiny ad:
Download Free Java APIs to Work with Office Files and PDF
htttp://www.e-iceblue.com/free-apis.html
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!