KnowledgeBoat Logo
|

Computer Applications

Correct the errors of the given program:

class Sample
{
public static void main(String args[])
{
int n,p;
float k,r;
n=25;p=12; 
if(n=25)
{
k=pow(p,2)
System.out.println("The value of"+p+ "= "+k);
}
else
{
r=Math.square root(n); 
System.out.println("The value of"+n+ "= "+r);
} 
} 
}

Input in Java

16 Likes

Answer

Errors in the snippet

  1. if(n=25) should be if(n==25)
  2. Correct way to call method pow is Math.pow(p,2);
  3. Return type of Math.pow is double. Variable k is of float type so return value should be explicitly casted to float.
  4. Math.square root(n) should be Math.sqrt(n)
  5. Return type of Math.sqrt is double. Variable r is of float type so return value should be explicitly casted to float.

Corrected Program

class Sample
{
public static void main(String args[])
{
int n,p;
float k,r;
n=25;p=12; 
if(n==25)       //1st correction
{
k=(float)Math.pow(p,2); //2nd & 3rd corrections
System.out.println("The value of"+p+ "= "+k);
}
else
{
r=(float)Math.sqrt(n);  //4th & 5th corrections
System.out.println("The value of"+n+ "= "+r);
} 
} 
}

Answered By

11 Likes


Related Questions