A point on the two-dimensional plane can be represented by two numbers: a X coordinate and a Y coordinate. For example, (4,5) represents a point 4 units to the right of the origin along the X axis and 5 units up the Y axis. The sum of two points can be defined as a new point whose X coordinate is the sum of the X coordinates of the points and whose Y coordinate is the sum of their Y coordinates.
Write a program that uses class point to model a point. Define data members X and Y coordinates. Create objects for point class, get data from user for two points, pass it using constructors. Use data member function SumPoint(obj1, obj2) to find the sum and return it. Use another member function Display() to display the new coordinates.
class Point {
double x;
double y;
Point(double x, double y) {
this.x=x;
this.y=y;
}
void setX(double x) { this.x=x; }
void setY(double y) { this.y=y; }
double getX() { return x; }
double getY() { return y; }
}
public class Main {
public static void main(String[] args) {
Point p1 = new Point(4, 5);
Point p2 = new Point(-2, 4);
Point p = add(p1, p2);
System.out.printf("RESULT: (%f, %f)\n", p.getX(), p.getY()); // (2, 9)
}
private static Point add(final Point p1, final Point p2) {
return new Point(p1.getX() + p2.getX(), p1.getY() + p2.getY());
}
}
Comments
Leave a comment