Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

dan's control flow questions

 
anushree ari
Ranch Hand
Posts: 98
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Dan Chisholm
Ranch Hand
Posts: 1865
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic