Search code examples
javamathsqrt

Cannot invoke sqrt(double) on the primitive type double


for some reason my code wont run i get the error "cannot invoke sqrt(double) on the primitive type double" thats the only error i get when i compile it so everything else doesn't cause an error except the Math.sqrt(math) line. Help?

public class Confused {

public static double average(int x, int y) {
double ave= (x+y)/2.0;
return ave;
}
public static double slope(int x1, int x2, int y1, int y2){
double slope= (y2-y1)/(x2-x1);
return slope; }

public static int difference(int x, int y) {
int diff=x-y;
return diff; }

public static int square(int x) {
int power1=(int)Math.pow(x, 2);
return power1;

}
 public static double distance (int x1, int x2, int y1, int y2) {
double Math= (square(difference(x2,x1))) + (square(difference(y2,y1)));
 double dist= Math.sqrt(Math);
return dist;

}

public static void main(String[] args) { 
  System.out.println(average(2,3));
  System.out.println(slope(1,2,3,4));
  System.out.println(difference(10,5));
  System.out.println(square(10));
  System.out.println(distance(2,3,6,8));

}

}

Solution

  • double Math= (square(difference(x2,x1))) + (square(difference(y2,y1)));
    double dist= Math.sqrt(Math);
    

    You're creating a new variable Math, on the next line you refer to that new variable since it shadows the global class Math. So its trying to call double.sqrt(double), which does not exist.