aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Question from Dan Chisholm's mock exam Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Question from Dan Chisholm Watch "Question from Dan Chisholm New topic
Author

Question from Dan Chisholm's mock exam

harsha puttaswamy
Greenhorn

Joined: Mar 05, 2005
Posts: 24
class JMM106 {
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));
}}

Answer is :- 1433.

Can someone please explain to me what exactly happens in the default section ? For some reason I am thinking x should be set to 2 in the first step because x will be less than 10. But, it turns out that x evaluates to -3 in the first step.

Thank you,
Harsha.
sethu chiyan
Greenhorn

Joined: Apr 05, 2005
Posts: 10
Hi Harsha,

// code here

default: x += x < 0 ? 2 : -2;// Evaluation explained below


In First time Loop

Current x value is -5 as v know

x+= (x<0) ? 2 : -2
x += (-5<0) ? 2: -2
x+=2;
so x = -3 in 1rst iteration


In second time Loop

Current x value is -3 as v know

x+= (x<0) ? 2 : -2
x += (-3<0) ? 2: -2
x+=2;
so x = -1 in 2nd iteration

In Third time Loop

Current x value is -1 as v know

x+= (x<0) ? 2 : -2
x += (-1<0) ? 2: -2
x+=2;
so x = 1 in 2nd iteration

Then as v know it goes like this
System.out.print("1");
System.out.print("4");
System.out.print("3");
System.out.print("3");

So the O/P is 1433.

Hope this will help u.

Pl do contact me if u r still in trouble,

with regards,
Chiyan.
harsha puttaswamy
Greenhorn

Joined: Mar 05, 2005
Posts: 24
Thank you Chiyan, that makes sense !!

Harsha.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Question from Dan Chisholm's mock exam