Straight and Distance between two points in java
The purpose of this article is to learn how to create a point with the coordinates x and y in a two-dimensional plane, then create a second point and calculate the distance between the two.1) Create the class Point
To structure our program well, We must avoid the creation of multiple instances of x and y (x1,x2,.. xn-y1,y2,.. yn). Java is an object-oriented language that has a high capacity for abstraction.
public class Point {
int x,y;
public Point(int x, int y){
this.x=x;
this.y=y;
}
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}
}
2) Create the class Line
A line is formed with at least two points P1 and P2, the distance is calculated by the Pythagorean theorem:
The Pythagorean theorem is applied when the triangle is rectangular, the formula is written: c² = a² + b². The length is then the root of c² and calculated using the method Math.sqrt().
public class Right {
dot p1, p2;
public Right (dot p1, dot p2){
this.p1=p1;
this.p2=p2;
}
double length(){
return p1.distance(p2);
}
}
Now we're going to declare the distance() method in the Point class that allows you to return the distance between the current point and the past point as a parameter:
double distance(Point p){
return Math.sqrt(((p.getX()-this.getX()) + (p.getY()-this.getY()));
}
Example
public class Main {
public static void main(String[] args) {
Point p1 = new Point(2, 3);
Point p2 = new Point(5, 8);
line Straight = new Straight (p1, p2);
System.out.println(Right.length());
Point p3 = new Point(7, 3);
System.out.println("distance between the point("+p1.getX()+", "+p1.getY()+
") and the point("+p2.getX()+", "+p2.getY()+": "+p1.distance(p3));
}
}
Output:
References: 2.8284271247461903
Distance between point(2, 3) and point(5, 8): 2.23606797749979
Wikipedia: Right(mathematics)
Wikipedia: Pythagorean theorem
Oracle Documentation: Math.sqrt