用java计算两点之间的距离
我对Java有点陌生,正在尝试编写一个代码来计算两点2和3的距离,以及10的刻度。不知何故,它不起作用。你能给我一个提示,这样我就能修改代码了吗用java计算两点之间的距离,java,object,Java,Object,我对Java有点陌生,正在尝试编写一个代码来计算两点2和3的距离,以及10的刻度。不知何故,它不起作用。你能给我一个提示,这样我就能修改代码了吗 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) {
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);
}
}
在“缩放”中,您将使用缩放值创建一个新点,但不使用该点。你把问题点的x和y保持不变 您可能想将x和y乘以因子,而不是创建一个新点 此外,您正在打印一个名为distance的变量,该变量不存在,因此它甚至可能不会编译,而不是调用名为distance的方法并打印其返回值。此时,您的distance方法正在计算点到原点的距离,即点0,0。如果你把这一点说清楚,那就更有意义了:
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);
}
}
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);
}
}
然后,查找到原点的距离就变成了point.distanceToPoint.origin,这使得意图更加清晰。也许您希望scale返回新的点,而不是factor?如果你这样做了,你可以写float p=newpoint2,3.scale10.distance;然后是System.out.printlnp;2和3不是点,它们是整数。或者你的意思是计算从二维空间中坐标为2,3的一个点到另一个点的距离,但我在你的代码中看不到这一点。那么,用数学术语来说,你想达到什么目的呢?