When you want to ask for help on a question from my web site, then you can post the question here as long as you say that the question came from my web site. When I see one of my questions with the name of the class changed, then it causes me to suspect that you found that question on a web site that has plagiarized my work. In the future, please don't change the name of the class and please specify that the question came from my web site. It would also be nice to provide the URL to the page where the question can be found.
In this case, if that question did not come from my web site, then please tell me where it came from.
The explanation for that question is as follows.
On the first pass through the loop, the switch expression, x, has the value, -5. None of the case constants are matched, so the statement following the default label is executed causing the value of x to be set to -3. On the second pass, the default case of the switch statement is executed again, and two is again added to the value of x. The new value is -1. On the third pass, the value of x is again incremented, and the new value is +1. After that, the value of x is printed on each pass through the loop. For the last two passes, the value of x is 3.
[ August 09, 2004: Message edited by: Dan Chisholm ]
Dan Chisholm<br />SCJP 1.4<br /> <br /><a href="http://www.danchisholm.net/" target="_blank" rel="nofollow">Try my mock exam.</a>
Hi Dan--I also had a doubt on this question about how x gets the value -3 from the expression default: x += x < 0 ? 2 : -2; x = x +x and i eavaluated it to -10 Can u correct me if i am wrong--I am sorry to ask something so fundamental.
Joined: Jul 02, 2002
The expression x += x < 0 ? 2 : -2 can be simplified as follows.
For the first three iterations of the do while loop, the default case of the switch statement executes (x changes from -5 to -3, -1, 1). After the first three iterations x is 1. In the fourth iteration of the loop, case 1 is executed which PRINTS 1 and changes x to 4. In the fifth iteration, case 4 is executed which PRINTS 4 and changes x to 3. In the sixth iteration, case 3 is executed which PRINTS 3 and changes success to 1. In the seventh iteration, case 3 is executed again which PRINTS 3 and changes success to 2. At this point, success is 2 and x is 3. So, the while condition is false and the loop terminates. Hence, the output is 1433.