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,因为您返回的是result
,它是Point的一个实例。如果你想要距离的双倍(值),你应该这样做:
//euclidean distance (?)
double 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.distance;
}
}
你得到一个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)坐标,但没有固有的距离。相反,“距离”是两点之间的关系。
在你的距离功能
Point distance (Point other) {
...
rest of your code
...
System.out.println(result); <-- you have tired to print out the object
return result;
}
要纠正您的问题,您需要打印出您正在寻找的对象的字段,即distance
System.out.println(result.distance);
一个建议
你可以将distance
的返回类型Point
函数更改为int
为什么?
因为返回对象Point
不代表距离的值