public class Point
{
// Placeholders for xcoordinate, ycoordinate, and quadrants
int xcoord = 0;
int ycoord =0;
double distance = 0.0;
String quadrant = ("NW");
//moveUp changes the y coordinate
void moveUp (int x) {
int moveUp = ycoord + x;
ycoord= moveUp;
System.out.println(moveUp);
}
// moveDown changes the y coordinate
void moveDown (int y){
int moveDown = ycoord - y;
ycoord =moveDown;
System.out.println(moveDown);}
// moveLeft changes the x coordinate
void moveLeft (int f){
int moveLeft = xcoord -f ;
xcoord = moveLeft;
System.out.println(moveLeft);}
// moveRight changes the x coordinate
void moveRight (int h) {
int moveRight = xcoord +h ;
xcoord = moveRight;
System.out.println(moveRight);}
// This takes the y coordinate and the xcoordinate and places it into a quadrant. Then it returns the quadrant.
String quadrant () {
if (xcoord >= 0 && ycoord >=0){
return quadrant = ("NE"); }
else if ( xcoord < 0 && ycoord < 0 ) {
return quadrant = ("SW");}
else if (xcoord <0 && ycoord >0 ){
return quadrant = ("NW");}
else if (xcoord >0 && ycoord <0){
return quadrant = ("SE");}
else {
return quadrant = ("Origin");}
}
//euclidean distance (?)
Point distance (Point other) {
Point result = new Point();
result.ycoord = Math.abs (ycoord - other.ycoord);
result.xcoord = Math.abs (xcoord- other.xcoord);
result.distance = Math.sqrt((result.ycoord)*(result.ycoord) +(result.xcoord)*(result.xcoord));
System.out.println(result);
return result;
}
}
这是完整的代码。我遇到的问题是由于某种原因我的距离方法无法正常工作,我不知道为什么。它返回 Point@24a42c89
,而不是任何数字。请让我知道为什么它返回这个而不是数字。非常感谢。我是初学者,对 Java 知之甚少。
最佳答案
您得到一个 Point
作为结果,因为您正在返回一个 Point
对象。在计算两点之间的距离时,没有理由声明一个 Point
对象。这里所有计算的结果都是数字,所以声明所有变量为double
:
double distance (Point other) {
double deltaX = ycoord - other.ycoord;
double deltaY = xcoord - other.xcoord;
double result = Math.sqrt(deltaX*deltaX + deltaY*deltaY);
return result;
}
请注意,不需要 Math.abs()
,因为两个数的平方总是得到非负数。
这也消除了在每个点中存储 distance
值的需要。这应该是有道理的,因为点是一对 (x, y) 坐标,但不具有固有距离。相反,“距离”是两点之间的关系。
关于Java方法获得欧氏距离,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26172891/