Java – Calculating the distance between two points

java

I need to create a class which calculates the distance between two points. I am stuck and I am a total beginner. Here are my classes:

package org.totalbeginner.tutorial;

public class Point {

    public double x;
    public double y;

    Point(double xcoord, double ycoord){
        this.x = xcoord;
        this.y = ycoord;
    }

    public double getX() {
        return x;
    }

    public double getY() {
        return y;
    }    
}

The second class.

package org.totalbeginner.tutorial;

public class Line {

    double x;
    double y;

    Point p1 = new Point(2.0,2.0);
    Point p2 = new Point(4.0,4.0);
    Point mp = new Point(x,y);

    public void midpoint() {
        x = (p1.getX() + p2.getX()) / 2;
        y = (p1.getY() + p2.getY()) / 2;
    }
}

I am not sure how to get a point object (the middle point) between both defined points.

I can create point objects but I am not sure how to return a point object through my midpoint() method that lies between those two point objects.

Best Answer

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