Distance between two points using Point Class
The Point class represents a point with x and y coordinates. Create a class Point according to the class diagram given below:
InputP1(x,y)=2,3
InputP2(x,y)=5,6
Output Should be:
The distance of P1 from Origin is 3.605551275463989
The distance of P1 from P2 is 4.242640687119285
Code:
package Com.Suryawanshi;
class Point{
private double x;
private double y;
public double getX() {
return x;
}
public void setX(double x) {
this.x = x;
}
public double getY() {
return y;
}
public void setY(double y) {
this.y = y;
}
public Point(double x, double y) {
this.x = x;
this.y = y;
}
public double distance(){
return Math.sqrt((this.getX())*(this.getX())+
(this.getY())*(this.getY()));
}
public double distance(Point point){
return Math.sqrt((this.getX()-point.getX())*(this.getX()-point.getX())+
(this.getY()- point.getY())*(this.getY()- point.getY()));
}
}
public class Tester {
public static void main(String[] args) {
Point p1x = new Point(2,3);
double totalDistanceOrigin = p1x.distance();
System.out.println("The distance of P1 from Origin is "+totalDistanceOrigin);
Point p2x= new Point(2,3);
Point p2y= new Point(5,6);
double totalDistancePoint = p2x.distance(p2y);
System.out.println("The distance of P1 from P2 is "+totalDistancePoint);
}
}
Comments
Post a Comment