无法在基本类型 double 上调用 sqrt(double)

Cannot invoke sqrt(double) on the primitive type double

出于某种原因,我的代码不会 运行 我收到错误 "cannot invoke sqrt(double) on the primitive type double" 那是我编译它时遇到的唯一错误,所以除了 Math.sqrt(数学)行。有帮助吗?

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));

}

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

您正在创建一个新变量 Math,在下一行中您引用了该新变量,因为它隐藏了全局 class Math。所以它试图调用 double.sqrt(double),它不存在。

您是 hiding 内置的 class Math,方法是将其用作变量。你可以做

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

由于 Math 是 Java 中的 class,您不能将其用作对象变量。而是使用其他一些变量名:

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