Question 0-2

Write a Point class to represent a point in two-dimensional Cartesian space. The point class should support the following methods.

Point()
Constructs a point at location (0,0) in the Cartesian plane.

Point(double x, double y)
Constructs a point at location (x,y) in the Cartesian plane.

void translate(double dx, double dy)
Moves the point by (dx, dy). In traditional Cartesian coordinates, this would move it dx units to the right and dy units up.

double distanceTo(Point other)
Computes the distance to other from the point asked. For example, if x is the point (0,0) and y is the point (3,4), then x.distanceTo(y) should return ((0-3)2 + (0-4)2)0.5 = 5.

You can use the following class to test your point.

import csbsju.cs160.*;

public class PointTest {
    public static void main(String[] args) {
        Point origin = new Point();
        Point pt = new Point(3, 4);

        IO.println(pt.distanceTo(origin)); // prints ``5.0''

        pt.translate(2, 8);
        IO.println(pt.distanceTo(origin)); // prints ``13.0''
    }
}

Solution

public class Point {
    private double my_x;
    private double my_y;

    public Point() {
        my_x = 0.0;
        my_y = 0.0;
    }

    public Point(double x, double y) {
        my_x = x;
        my_y = y;
    }

    public double distanceTo(Point other) {
        return Math.sqrt(Math.pow(my_x - other.my_x, 2.0)
            + Math.pow(my_y - other.my_y, 2.0));
    }

    public void translate(double dx, double dy) {
        my_x += dx;
        my_y += dy;
    }
}

Back to Exercise Set 0