Win a copy of Clojure in Action this week in the Clojure forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

SCJP book by K&B q1 page 389

 
sapana jain
Ranch Hand
Posts: 42
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Given the following code:
public class OrtegorumFunction
{
public int computeDiscontinuous(int x)
{
int a = 1;
a += x;
if ((x > 4) && (x < 10))
{
a += 2 * x;
}
else (x <= 4)
{
a += 3 * x;
}
else
{
a += 4 * x;
}
a += 5 * x;
return a;
}
public static void main(String [] args)
{
OrtegorumFunction o = new OrtegorumFunction();
System.out.println("OF(11) is: " + o.computeDiscontinuous(11));
}
}
What is the result?
A. OF(11) is: 45
B. OF(11) is: 56
C. OF(11) is: 89
D. OF(11) is: 111
E. Compilation fails.
F. An exception is thrown at runtime.
Answer:
E is correct. The if statement is illegal. The if-else-else must be changed to if-else if-else, which would result in OF(11) is: 111.

now the problem is when i am giving the if-else if-else the output is coming to be.144,so i got confused.Please help actually when i am running the code on paper also my output is coming 111.........so what is actually happening.........
 
Meher Parveen
Greenhorn
Posts: 25
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Could you post the altered code with if-else if-else blocks.
 
Meher Parveen
Greenhorn
Posts: 25
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
i get 111 as the output when i get rid of the compile error....
see the code below:
public class OrtegorumFunction
{
public int computeDiscontinuous(int x)
{
int a = 1;
a += x;
if ((x > 4) && (x < 10))
{
a += 2 * x;
}
else if (x <= 4)
{
a += 3 * x;
}
else
{
a += 4 * x;
}
a += 5 * x;
return a;
}

public static void main(String [] args)
{
OrtegorumFunction o = new OrtegorumFunction();
System.out.println("OF(11) is: " + o.computeDiscontinuous(11));
}
}
 
I agree. Here's the link: http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic