[Solved] calculate the length of line using toString


The toString() method of the Point class should look like:

public String toString() {
   return "(" + x + "," + y + ")";
}

The toString() method of the Line class should look like (supposing you have two members of type Point in the class Line):

public String toString() {
   return "(" + point_A.getX() + "," + point_A.getY() + ")->" +
          "(" + point_B.getX() + "," + point_B.getY() + ");
}

Mathematically, if you have two points: A(x1, y1) and B(x2, y2), the length of the line AB will be calculated with this formula:

AB * AB = (x2 - x1)*(x2 - x1) + (y2 - y1)*(y2 - y1)

Thus, you can do the following thin in your code:

Double length = Math.sqrt((x2 - x1)*(x2 - x1) + (y2 - y1)*(y2 - y1));
System.out.println(length);

0

solved calculate the length of line using toString