# Answer to Question #4927 in Java | JSP | JSF for mohamad

Question #4927
java class to calculate the distance between two points.
1
2011-11-03T11:34:00-0400
The distance between two points (x1,y1) and (x2,y2) on a flat surface is:

d = sqrt((y2 - y1)^2& + (x2 - x1)^2)

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

public Punkt mittelpunkt (Punkt p1, Punkt p2) {
return new Punkt ((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&#039;d make some minor changes.

First Punkt.java:

class Punkt {
double x, y;
Punkt (double xkoord, double ykoord) {
& this.x = xkoord;
& this.y = ykoord;
}
public double getX() {
& return x;
}
public double getY() {
& return y;
}
}
Then Strecke.java:

public class Strecke {
Punkt p1, p2;
Strecke (Punkt punkt1, Punkt punkt2) {
& this.p1 = punkt1;
& this.p2 = punkt2;
}
public Punkt mittelPunkt() {
& return new Punkt ((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[]) {
& Strecke s = new Strecke (new Punkt(2.0, 2.0), new Punkt(5.0, 6.0));
& Punkt mp = s.mittelPunkt();
& System.out.println (&quot;Midpoint = (&quot; + mp.getX() + &quot;,&quot; + mp.getY() + &quot;)&quot;);
& double as = s.abstand();
& System.out.println (&quot;Length = &quot; + as);
}
}
These two files, when compiled and run, generate the correct:

Midpoint = (3.5,4.0)
Length = 5.0

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!