File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
Win a copy of Clojure in Action this week in the Clojure forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Confusing Switch

 
Vinod Sinha
Ranch Hand
Posts: 43
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 6
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 43
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 8927
Firefox Browser Java Spring
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
I agree. Here's the link: http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic