Granny's Programming Pearls
"inside of every large program is a small program struggling to get out"
JavaRanch.com/granny.jsp
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Confusing Switch Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Confusing Switch" Watch "Confusing Switch" New topic
Author

Confusing Switch

Vinod Sinha
Ranch Hand

Joined: Oct 16, 2003
Posts: 43
class JMM105 {
public static void main(String args[]) {
int x = 6; int success = 0;
do {
switch(x) {
case 0: System.out.print("0"); x += 5; break;
case 1: System.out.print("1"); x += 3; break;
case 2: System.out.print("2"); x += 1; break;
case 3: System.out.print("3"); success++; break;
case 4: System.out.print("4"); x -= 1; break;
case 5: System.out.print("5"); x -= 4; break;
case 6: System.out.print("6"); x -= 5; break;
}
} while ((x != 3) || (success < 2));
}}
Output is coming as 61433 which matches with the answer Dan has given
but my doubt is --
After 614 is printed , x is changed to 3. So , the loop should stop
since the while condition of X!=3 is no longer satisfied.
Then how is the loop progressing even after that ?
Maybe i am missing some important point !!
Hushar Punekar
Greenhorn

Joined: Oct 22, 2003
Posts: 6
while ((x != 3) || (success < 2));
will evaluate to true if any of the conditions is true. i.e. even if x is 3 (hence first condition is false) success is less than 2 (hence second condition is true) This allows it to go through the switch statement two more times until success is no longer less than 2.
Hope this helps. (if not, open any (good) data structurs book and learn the AND, OR, boolean AND, boolean OR rules)
-Suhas
Vinod Sinha
Ranch Hand

Joined: Oct 16, 2003
Posts: 43
thanks hushar ! I know AND OR NOT very well. its only that i took OR as AND in a hurry. I hope not to make such silly mistakes in the exam !
Pradeep bhatt
Ranch Hand

Joined: Feb 27, 2002
Posts: 8904

Originally posted by Vinod Sinha:
thanks hushar ! I know AND OR NOT very well. its only that i took OR as AND in a hurry. I hope not to make such silly mistakes in the exam !

//
Usually we concentrate less in mock exams so we make silly mistakes. In real exam though we concetrate hard and silly mistakes are avoided.. that is what I feel. Good luck for the exam.


Groovy
 
jQuery in Action, 2nd edition
 
subject: Confusing Switch
 
Similar Threads
I thought I understood this stuff.....
dan's control flow questions
Flow control!
switch statement
Dans Questions : logic