[英]Calculate distance between two points in java
I'm kind of new to Java, and trying to write a code that calculate the distance of two points 2 and 3, and scale of 10. Somehow, it does not work. 我是Java的新手,尝试编写代码来计算两个点2和3的距离以及10的比例。某种程度上,它不起作用。 Can you give me a hint, so I can fix the code?
您能给我一个提示,以便我解决此问题吗?
import java.lang.Math;
public class Point {
int x, y;
public Point (int x, int y){
this.x = x;
this.y = y;
}
public float scale(int factor) {
new Point(x * factor, y * factor);
return factor;
}
public float distance(){
double distance = Math.sqrt(x * x + y * y);
return distance;
}
public void main(String[] args) {
float p = new Point(2,3).scale(10);
System.out.println(distance);
}
}
In scale you are creating a new point with the scaled values and doing nothing with it. 在缩放中,您正在使用缩放后的值创建一个新点,而对其不执行任何操作。 You're leaving x and y of the point in question untouched.
您将保持原样的x和y不变。
You probably mean to multiply x and y by factor, rather than creating a new point. 您可能打算将x和y乘以系数,而不是创建一个新点。
Also you're printing a variable named distance, which does not exist (so this probably doesnt even compile), rather than calling the method named distance() and printing its returned value. 另外,您将打印一个名为distance的变量,该变量不存在(因此甚至可能不会编译),而不是调用名为distance()的方法并打印其返回值。
public class Point {
int x, y;
public Point (int x, int y){
this.x = x;
this.y = y;
}
public static Point scalePoint(Point p, int factor) { //scale a given point p by a given factor
Point scaledPoint = new Point(p.x * factor, p.y * factor); //by multipling the x and y value with the factor
return scaledPoint; //and return the new scaled point
}
public static double calculateDistance(Point p1, Point p2){ //to calculate the distance between two points
double distance = Math.sqrt(p1.x * p2.x + p1.y * p2.y); //send the two points as parameter to this method
return distance; //and return the distance between this two as a double value
}
public static void main(String[] args) {
Point p = new Point(2,3);
Point scaledPoint = scalePoint(p, 10);
double distance = calculateDistance(p, scaledPoint);
System.out.println(distance);
}
}
At the moment your distance
method is calculating the distance of a point from the origin (ie point 0,0). 目前,您的
distance
方法正在计算一个点到原点(即点0,0)的距离。 It would make more sense if you made that explicit: 如果您明确指出,它将更有意义:
class Point {
private static final Point ORIGIN = new Point(0, 0);
private final int x;
private final int y;
public float distanceTo(Point other) {
float xDelta = other.x - this.x;
float yDelta = other.y - this.y;
return Math.sqrt(xDelta * xDelta + yDelta * yDelta);
}
public Point scale(float factor) {
return new Point(x * factor, y * factor);
}
}
Then finding the distance to the origin becomes point.distanceTo(Point.ORIGIN)
which makes the intent clearer. 然后找到到原点的距离变为
point.distanceTo(Point.ORIGIN)
,这使意图更清晰。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.