计算java中两点之间的距离

时间:2016-09-14 05:51:49

标签: 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) {
        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);
    }

    }

3 个答案:

答案 0 :(得分:4)

在比例尺中,您正在使用缩放值创建一个新点,并且不执行任何操作。你没有触及有问题的点的x和y。

你可能意味着将x和y乘以因子,而不是创建一个新点。

此外,您还打印了一个名为distance的变量,该变量不存在(因此这可能甚至无法编译),而不是调用名为distance()的方法并打印其返回值。

答案 1 :(得分:1)

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);
    }
}

答案 2 :(得分:1)

目前,您的Dispose()方法正在计算点与原点的距离(即点0,0)。如果你明确指出它会更有意义:

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); } } ,这使得意图更清晰。