Calculating the distance between two points

The distance between two points (x1,y1) and (x2,y2) on a flat surface is:

    ____________________
   /       2          2
 \/ (y2-y1)  + (x2-x1)

But, if all you want is the midpoint of your two points, you should change your midpoint function to:

public Point midpoint (Point p1, Point p2) {
    return new Point ((p1.getX() + p2.getX()) / 2, (p1.getY() + p2.getY()) / 2);
}

This will return a brand new point object with the points set to the middle of the given two points (without having to concern yourself with any other math). And, since your second class is a line, you only need the two end points to describe it, so I’d make some minor changes.

First Point.java:

class Point {
    double x, y;
    Point (double xcoord, double ycoord) {
        this.x = xcoord;
        this.y = ycoord;
    }
    public double getX() { return x; }
    public double getY() { return y; }
}

Then Line.java:

public class Line {
    Point p1, p2;
    Line (Point point1, Point point2) {
        this.p1 = point1;
        this.p2 = point2;
    }
    public Point midpoint() {
        return new Point ((p1.getX()+p2.getX())/2, (p1.getY()+p2.getY())/2);
    }
    public double abstand() {
        return Math.sqrt(
            (p1.getX() - p2.getX()) *  (p1.getX() - p2.getX()) + 
            (p1.getY() - p2.getY()) *  (p1.getY() - p2.getY())
        );
    }
    static public void main (String args[]) {
        Line s = new Line (new Point(2.0, 2.0), new Point(5.0, 6.0));
        Point mp = s.midpoint();
        System.out.println ("Midpoint = (" + mp.getX() + "," + mp.getY() + ")");
        double as = s.abstand();
        System.out.println ("Length   = " + as);
    }
}

These two files, when compiled and run with the endpoints 2,2 and 5,6 (the hypotenuse of a classic 3/4/5 right-angled triangle), generate the correct:

Midpoint = (3.5,4.0)
Length   = 5.0

Leave a Comment