KnowledgeBoat Logo
|

Computer Applications

Correct the errors of the given program:

class Square
{
public static void main(String args[])
{
int n=289,r;
r=sqrt(n);
if(n==r)
System.out.println("Perfect Square");
else
System.out.println("Not a Perfect Square");
}
}

Input in Java

34 Likes

Answer

Errors in the snippet

  1. Math.sqrt(n) is the correct way to call sqrt method of Math class.
  2. As Math.sqrt(n) returns double value, so the return value should be explicitly casted to int.

Corrected Program

class Square
{
public static void main(String args[])
{
int n=289,r;
r=(int)Math.sqrt(n);    //1st & 2nd Corrections
if(n==r)
System.out.println("Perfect Square");
else
System.out.println("Not a Perfect Square");
}
}

Answered By

21 Likes


Related Questions