Win a copy of TDD for a Shopping Website LiveProject this week in the Testing 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 Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Paul Clapham
  • Ron McLeod
  • Jeanne Boyarsky
  • Tim Cooke
Sheriffs:
  • Liutauras Vilda
  • paul wheaton
  • Henry Wong
Saloon Keepers:
  • Tim Moores
  • Tim Holloway
  • Stephan van Hulst
  • Carey Brown
  • Frits Walraven
Bartenders:
  • Piet Souris
  • Himai Minh

switch statement - default case first

 
Ranch Hand
Posts: 41
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator


The first switch prints ABdef.

Whereas the second switch prints B.

This is pretty strange. Anyone have an explaination??
 
Greenhorn
Posts: 11
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi Robert

pretty tricky example.
Watch out for println and print in the code.

The first switch will print "AB", while the second switch will print "def" (on the same line) and "B" (on the next line).

Changing the code to this will make it more clear:



and the result will be:

ABnext switch
def
B
 
Ranch Hand
Posts: 453
Google Web Toolkit Hibernate Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
change all the print to println then you will get to know there is nothing wrong in your concept.its the dingy way of coding which is making the difference.

avi
 
lowercase baba
Posts: 13048
67
Chrome Java Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
In your original code, the execution goes like this. The default case is skipped. case 9 is true so we print the 'A' with no new line. since there is no break, we go ahead and print the 'B', with no new line

you then enter the second case statement. since none of the conditions match, you drop to the 'default' case, and print 'def', with the new line. so, at this point, you see

ABdef

again, there is no break, so we execute the next line, which is the printing of the 'B'.
 
Cob is sand, clay and sometimes straw. This tiny ad is made of cob:
Free, earth friendly heat - from the CodeRanch trailboss
https://www.kickstarter.com/projects/paulwheaton/free-heat
reply
    Bookmark Topic Watch Topic
  • New Topic