In: Computer Science
Java question: I need to fix a point class (code below) Thank you!
/** * A point, implemented as a location without a shape. */ public class Point extends Location { // TODO your job // HINT: use a circle with radius 0 as the shape! public Point(final int x, final int y) { super(-1, -1, null); assert x >= 0; assert y >= 0; } }
import java.util.Objects;
public final class Point {
private double x; // x-coordinate
private double y; // y-coordinate
// no parameter constructor to generate random point
public Point() {
x = (Math.random() * (1.0 - 0.0 + 1) + 0.0);
y = (Math.random() * (1.0 - 0.0 + 1) + 0.0);
}
// parameterized constructor
public Point(double x, double y) {
this.x = x;
this.y = y;
}
// getters
public double getX() { return x; }
public double getY() { return y; }
// Euclidean formula to find distance between two points.
public double distanceTo(Point point) {
double dx = this.x - point.x;
double dy = this.y - point.y;
return Math.sqrt(dx*dx + dy*dy);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Point point = (Point) o;
return Double.compare(point.x, x) == 0 &&
Double.compare(point.y, y) == 0;
}
@Override
public int hashCode() {
return Objects.hash(x, y);
}
public String toString() {
return "(" + x + ", " + y + ")";
}
// driver method
public static void main(String[] args) {
Point p1 = new Point();
System.out.println("p = " + p1);
System.out.println(" x = " + p1.getX());
System.out.println(" y = " + p1.getY());
System.out.println();
Point p2 = new Point(0.5, 0.5);
System.out.println("q = " + p2);
System.out.println(" x = " + p2.getX());
System.out.println(" y = " + p2.getY());
System.out.println("dist(p, q) = " + p1.distanceTo(p2));
//prints point p1 equals p2 or not
System.out.println("Is p1 point equals p2 point? " + p1.equals(p2));
}
}
Output:
p = (0.8087211080759387, 1.0236249374819213)
x = 0.8087211080759387
y = 1.0236249374819213
q = (0.5, 0.5)
dist(p, q) = 0.6078583697906786
Summary:
Above program is written to represent a point by taking x and y coordinates. x and y are made private so that they are no manipulated outside the Point class.
Point class contains two different constructor one parameterized constructor to create point based on the x and y values provided and another no parameter constructor to generate random point.
In main method p1 point is generated randomly and p2 is user defined point as we are setting x and y coordinates manually.
Point class also has distanceTo method to get the distance between 2 points.