class Point {
duoble x,y,z;
Point(double _x,double _y,double _z) {
x = _x;
y = _y;
z = _z;
}
void pointX(double _x) {
x = _x;
}
void pointY(double _y) {
y = _y;
}
void pointZ(double _z) {
z = _z;
}
double distance(double _x,double _y,double _z) {
return ((_x - Point.x)*(_x - Point.x) + (_y - Point.y)*(_y - Point.y) + (_z - Point.z)*(_z - Point.z));
}
}public class TestPoint {
public static void main(String []args) {
Point i = new Point(1.0,2.0,3.0);
System.out.println(i.distance(3.0,3.0,3.0));
}
}
算距离的平方,但是为什么会报错这个错误类?到底是怎么回事,求教大神!!
duoble x,y,z;
Point(double _x,double _y,double _z) {
x = _x;
y = _y;
z = _z;
}
void pointX(double _x) {
x = _x;
}
void pointY(double _y) {
y = _y;
}
void pointZ(double _z) {
z = _z;
}
double distance(double _x,double _y,double _z) {
return ((_x - Point.x)*(_x - Point.x) + (_y - Point.y)*(_y - Point.y) + (_z - Point.z)*(_z - Point.z));
}
}public class TestPoint {
public static void main(String []args) {
Point i = new Point(1.0,2.0,3.0);
System.out.println(i.distance(3.0,3.0,3.0));
}
}
算距离的平方,但是为什么会报错这个错误类?到底是怎么回事,求教大神!!
2.类名.属性要求属性是static的
像你这个应该用this.x、this.y、this.z
class Point {
Double x, y, z; public Double getX() {
return x;
} public void setX(Double x) {
this.x = x;
} public Double getY() {
return y;
} public void setY(Double y) {
this.y = y;
} public Double getZ() {
return z;
} public void setZ(Double z) {
this.z = z;
} Point(double _x, double _y, double _z) {
x = _x;
y = _y;
z = _z;
} void pointX(double _x) {
x = _x;
} void pointY(double _y) {
y = _y;
} void pointZ(double _z) {
z = _z;
} double distance(double _x, double _y, double _z) {
return ((_x - x) * (_x - x) + (_y - y) * (_y - y) + (_z - z) * (_z - z));
}}class TestPoint {
public static void main(String[] args) {
Point i = new Point(1.0, 2.0, 3.0);
System.out.println(i.distance(3.0, 3.0, 3.0));
}}
class Point {
double x,y,z;
Point(double _x,double _y,double _z) {
x = _x;
y = _y;
z = _z;
}
void pointX(double _x) {
x = _x;
}
void pointY(double _y) {
y = _y;
}
void pointZ(double _z) {
z = _z;
}
double distance(Point p) {
return ((x - p.x)*(x - p.x) + (y - p.y)*(y - p.y) + (z - p.z)*(z - p.z));
}
}public class TestPoint {
public static void main(String []args) {
Point i = new Point(1.0,2.0,3.0);
Point p = new Point(3.0,3.0,3.0);
System.out.println(i.distance(p));
}
}
的是输出对象i执行方法“distance”的值,但是我在方法“distance”里面根本
就没有定义变量x,y,z,所以报错。后面的在方法“distance”里面有使用参数
“Point p”,而那个参数有定义变量x,y,z,所以不会报错,不知道这样理解对不对?
distance方法里面没有定义,但是类里面定义了啊,类的成员函数可以访问自己的成员变量的。
你第一个之所以报错,是因为你用Point.x。只有static的属性才可以直接用类.属性
成员变量的访问应该用(类的实例化对象).属性。比如这个p就是Point的一个对象。
在类内部,使用成员变量时可以用this.属性,比如this.x。
当然在不引起冲突的情况下,也可以直接写x。
public void setX(Double x1) {
x = x1;//等同于this.x=x1;
}
但是
public void setX(Double x) {
this.x = x;
}
这里的this.就不能省略。
return ((_x - Point.x)*(_x - Point.x) + (_y - Point.y)*(_y - Point.y) + (_z - Point.z)*(_z - Point.z)); 改为
return ((_x - this.x)*(_x - this.x) + (_y - this.y)*(_y - this.y) + (_z - this.z)*(_z - this.z));
后就可以了。