| 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>
|
 |
 |
|
|
subject: dan's control flow questions
|
|
|