This week's giveaways are in the MongoDB and Jobs Discussion forums.
We're giving away four copies of Mongo DB Applied Patterns and 4 resume reviews from Five Year Itch and have the authors/reps on-line!
See this thread and this one for details.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes  dan's control flow questions Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login


Win a copy of Mongo DB Applied Patterns this week in the MongoDB forum
or a resume review from Five Year Itch in the Jobs Discussion forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Reply Bookmark " dan Watch " dan New topic
Author

dan's control flow questions

anushree ari
Ranch Hand

Joined: Sep 30, 2002
Posts: 98
hi ranchers,
i came acroess this questions from dan's topic exam,

class Violet {
public static void main(String args[]) {
int x = -5;
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;
default:
x += x < 0 ? 2 : -2;
}
} while ((x != 3) || (success < 2));
}
}
the result is 1433, how?,
anybody pls explain,
thx


anushree
Dan Chisholm
Ranch Hand

Joined: Jul 02, 2002
Posts: 1865
The values of x for each pass through the loop are as follows.
-5, -3, -1, 1, 4, 3, 3
X starts as -5. The default case is used on the first pass through the loop and 2 is add to the value of x. The new value is -3. On the second pass, 2 is added again in the default case of the switch statement. The new value is -1. On the third pass 2 is added again in the default case. The new value is positive one. After that, the value of x is printed on each pass through the loop.


Dan Chisholm<br />SCJP 1.4<br /> <br /><a href="http://www.danchisholm.net/" target="_blank" rel="nofollow">Try my mock exam.</a>
 
I agree. Here's the link: http://ej-technologies/jprofiler - if it wasn't for jprofiler, we would need to run our stuff on 16 servers instead of 3.
 
subject: dan's control flow questions
 
Similar Threads
Flow control!
I thought I understood this stuff.....
Confusing Switch
switch statement
Dans Questions : logic